At the latest Google I/O conference, Google announced that Android development would now fully support Kotlin. This is big news as it opens up an entirely new avenue for those that want to start creating their own Android applications. And seeing as Kotlin is highly popular and has a lot of unique features, it creates new opportunities for existing developers too.

Kotlin is a statically typed programming language from JetBrains. It is fully ‘inter-operable’ with Java (meaning you can use Java frameworks and even mix commands from both in your code) and comes with no limitations. Android developers have actually been using Kotlin for some time already via a plugin and some popular apps on the Play Store (like Basecamp) were reportedly built solely using Kotlin. Now though, as of the forthcoming Android Studio 3.0, it will be bundled-in and supported out-of-the-box.

Kotlin allows us to remove significant amounts of boilerplate

So why would you choose to use Kotlin rather than Java? Well, the main reason is that it can make your life a little easier in a number of instances. Kotlin eliminates null references for example and it doesn’t have checked exceptions – both of which can save devs some headaches. As you’ll see, various features of Kotlin also allow us to remove significant amounts of boilerplate code too, resulting in cleaner, more readable programs. Generally, this is a more modern language and if you’re not already deeply entrenched in Java or keen to stick with the ‘most official’ method, then it might be worth considering. For those just getting started, Kotlin might represent a more forgiving learning curve.

So, for those interested in adopting Kotlin into their workflow, how might one go about getting stuck in?

Getting set up

The good news is that seeing as Kotlin is packaged in with Android 3.0 onwards, there will be no need to download anything new and only very minimal set-up involved. The bad news is that Android Studio 3.0 is still in beta, so to get that you’re going to have to download it separately from here. Extract all the files and then run bin > studio64.exe and you’re in. Welcome to the future!

Note that Android 3.0 is still in beta and as such, you should expect to run into occasional glitches. Never fear if you’d rather stick with regular old 2.3.2 though; you can still download the plugin by navigating to File > Settings > Plugins > Install JetBrains Plugin, searching for Kotlin and hitting ‘install’.

If you have Android Studio 3.0, then when you create a new project you’ll be given the option to include Kotlin support. If you tick this box, then you won’t need to configure your project later on.

Once you’ve set up a new project, open up MainActivity.java and then invoke the action: Convert Java File to Kotlin File. To do this, go to Help > Find Action and then start typing ‘Convert Java File…’. You’ll know it when you see it.

Now your code will change slightly from Java to Kotlin. It has the word ‘fun’ in it… I like it already! The extension for Kotlin files is ‘.kt’.

If you’re not using Android 3.0, you may now see a notice telling you that Kotlin is not yet configured. So as you might have already guessed, you need to configure it! Just go to Tools > Kotlin > Configure Kotlin (or click the prompt). You’ll be asked to choose a version and it’s generally advisable to pick the latest available.

If this goes according to plan, then your module-wide Gradle file should be updated to reflect the changes. If you want to check, then look for the line: apply plugin: ‘kotlin-android’ and a dependency for kotlin-stdlib. If that’s all in place, then you can sync your project and everything should be ready to go. You can now start coding in Kotlin just as you normally would in Java.

Either way, you’re now ready to start developing with Kotlin!

Note that it is usually a good idea to create a new directory for your Kotlin files, or to replace your java folder entirely if you’re using purely Kotlin from here on in. You can create new Kotlin files by right clicking the target directory and then select New > Kotlin Activity.

Hello Kotlin: some basic syntax and differences

Okay, let’s take a look at the code we already have. First, you might notice that you declare classes using class just as you would in Java. The difference is that there’s no public keyword, which is because all classes in Kotlin are public and final. You might also notice that we aren’t using extend either. Instead, we use a colon which does the same thing.

What about that fun command? This is actually short for ‘function’ (not so fun), so instead of writing public void, you’ll now write fun. This then leads our class a public function that we can call from other classes. Arguments are specified in brackets following the function name. To do this, you’ll need to know how to define variables, which is a little different. To create a string, you might write:

 JAVA  SELECT ALL
 JAVA  SELECT ALL
 var text: String = “Hello”

Although actually, Kotlin is usually smart enough to identify a variable’s type on its own just like Python, so you can generally just write:

 JAVA  SELECT ALL
 JAVA  SELECT ALL
 var text = “Hello”

To create a string, or:

 JAVA  SELECT ALL
 JAVA  SELECT ALL
 var num = 3

To create an integer. This is how you would create a mutable (changeable) variable. val is used to create constants. So when creating functions with arguments,  that’s what you’ll see in the brackets. And these variables can have default values, which is also handy. So you might see something like this:

 JAVA  SELECT ALL
 JAVA  SELECT ALL
fun SayHello(var userName : String = “User”) {                 textView.setText(“Hello, $userName!”)}

There’s one more big difference you may have spotted by now too… no semicolons! You’re free to include them if you want to but there is no longer an obligation and you won’t get penalized if you miss one. If you’re someone who still always forgets one somewhere, then this might come as good news!

You’ll notice lots of other little differences to the syntax as you go and of course, it’s beyond the scope of this post to list all of them here. However, the structure is still fairly similar, so, on the whole, you should be able to deduce what everything does from the context and perhaps with a little trial and error. You’ll find a great introduction here.

The true power of Kotlin: helping you type less

A lot of the time, code will look a fair bit simpler and shorter in Kotlin as compared with Java. Consider the following example of adding an onClickListener to a FAB. Here is how you would do it in Java:

 JAVA  SELECT ALL
 JAVA  SELECT ALL
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { … } });

And this is the same thing in Kotlin:

 JAVA  SELECT ALL
 JAVA  SELECT ALL
val fab = findViewById(R.id.fab) as FloatingActionButton fab.setOnClickListener { … }
It’s just a lot simpler and more straightforward and it makes for more readable code as you go. Like I said: less boilerplate. And actually, it goes a lot deeper than this. Kotlin developers can do away with ever having to write that findViewByID again! To do this, you need to apply a plugin.

You do this in the module-level build.gradle file by adding the line:

 XML  SELECT ALL
 XML  SELECT ALL
 apply plugin: ‘kotlin-android-extensions’

Click ‘sync’ and you’ll then be able to import references to your views right at the top of your code, like so:

 XML  SELECT ALL
 XML  SELECT ALL
import kotlinx.android.synthetic.main.<layout>.<view-id>

 

By doing this, you’ll then be able to access the view directly with no need to use its ID. This makes life much simpler and can save you writing a lot of arbitrary code.

Throw in lambda expressions and your code starts to get very concise indeed. Lambda expressions are anonymous functions that let you further reduce the amount you need to write by putting everything onto a single line. The statement is surrounded by curly brackets, containing parameters followed by an arrow symbol and then the body. For example, an onClickListener can look like this:

 JAVA  SELECT ALL
 JAVA  SELECT ALL
 button.setOnClickListener({ view -> toast(“Clicked!”) })

And if the function requires another function as the last parameter, you can pass it outside the parentheses:

 JAVA  SELECT ALL
 JAVA  SELECT ALL
button.setOnClickListener() { toast(“Clicked!”) }

 

Combining these techniques you can save yourself a whole lot of busywork and you’ll find many more useful time-saving strategies going forward.

Going forward

And there you have it: that’s Kotlin in a nutshell. Is it right for you? Ultimately, this comes down to personal preference and your sensibilities when it comes to coding. Personally, I’m a fan of the streamlined nature of Kotlin and the way it removes a lot of unnecessary lines of code. Hopefully, this post has given you enough of a primer that you can make your own mind up and continue your education if you decide it’s of interest. If you want to have a little play around, then you can try Kotlin in your browser here.

Whatever you decide, having more options is only ever a good thing!

Written by: Adam Sinicki

Source: Android Authority

Interesting Links:

Post Views: 1022