- SOLD IN 30 MINUTES | THE FIRST 15 MINUTES -

It's not the first language that does it, but it is the best. The JVM has several languages next to Java that target it. Notable examples are Scala and Groovy, however Kotlin is the language that may very well be the language that will trump all the others in the near future.

TL;DR I really want you to see the cool stuff, so if you do not care for background and introductory things, just continue with Part 2, to see the 'The cool stuff'. This first part tackles setting up Kotlin in your project and reading your first lines.

Kotlin is a statically typed language, crafted by JetBrains. I hope most of you already know this company, but if you do not, they are the people behind IntelliJ, which is the basis of many other IDE's. Amongst others, Appcode, Webstorm and of course Android Studio. Their first gem years ago was ReSharper. All of their products - except ReSharper - are written in Java. However they missed some features from other languages, that are simply not present in Java. Kotlin was born because of a need of a richer environment language wise. 5 to 6 years ago Scala was already present, but that wasn't good enough; mostly due to performance reasons, interoperability with Java and the complexity it brings. So they set out to do it themselves. Making a more feature rich language, while maintaining perfect operability with Java. It's open source (under the Apache 2.0 license) and while still in beta, it is already in used in mission critical production code. For it to be successful they hope it will be adopted by the community, so here's my 2 cents.
Next to targeting the JVM, it can also target JavaScript, but full support is planned post version 1.0.

The name of the language comes from an island near St. Petersburg - Russia. The team that started the development on Kotlin is located in that city. I guess they were joking a bit on the fact that Java is an island, since Kotlin is an island near St. Petersburg. The image above this post however, is totally unrelated to that island.

But why would you want it?

That's a very good question! Why would anyone want to invest in making a new language, and why should you invest in this hipster stuff? Well, the answer can come in many different forms, but the most compelling method is the following.

Spend no more than 30 minutes in getting the basics and make your first classes. You're either sold, or not.

If you are not convinced, or at least curious to learn more, stop. Otherwise, let your excitement pave the way for all the Kotlin goodness flow into your brain. Kotlin fixes a lot of the things Java just can't. Especially on Android, where we just can't follow Java 6, 7, 8, ... releases, due to non-upgradable phones. But even if you would be able to use the latest Java, then still Kotlin is more rich. Below I'll show some examples of my favorite outtakes, for now you could skip to the official docs for a comparison to Java:

  • Concise; You'll need less code to achieve things.
  • Safe; Say goodby to NullPointers.
  • Extensibility; No more need for Helper or Util classes.
  • Toolable; JetBrains, being a tooling company, will maximise the heavy lifting that the IDE can do.
  • Interoperable; Reuse any Java class ever written, all Java code can work with Kotlin and vice versa. Kotlin classes are compiled directly into class files.

Learning Kotlin for a Java developer shouldn't be to hard. Everything you can do with Java, you can do in Kotlin. If you do not know how to do it in Kotlin, then just do it in Java and let the Kotlin plugin convert it to Kotlin... Make sure that you see what happened to your code, so that the next time you can do it yourself.

The basics

Below steps will guide you through your first moments with Kotlin. Choose to follow them by the letter, or try the idea of it on your own project.

Step 1: Plugin

The first thing you need is the Kotlin plugin. Open up IntelliJ or Android Studio and find your way to Preferences->Plugins. In the plugins search bar enter 'Kotlin'. You'll find a plugin by JetBrains, install it and restart your IDE.

Plugins

Step 2: Pet project

Then you need a pet project, you can choose your own, or just follow my happy walkthrough. I choose to just create a new project using the wizard, selecting the Blank Activity with FAB.

New Project

Step 3: Enter Kotlin

Now find the main package of your project, mine is under app/java/nl.endran.kotlinftw. Right mouse click and select new->Kotlin class, name your class and make sure you select in the kind box Class.

New Class

In the right hand upper corner a popup will appear, asking if you want to configure your project for Kotlin, obviously this is what you want... Click it!!

New Class

Now your gradle file will have been updated, that's toolability alright ;)

New Class

Do yourself a favour and add just below the Kotlin classpath entry (line 39 in the image) the lines below. I'll explain later.

classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"  

Step 4: Reading some Kotlin

Alright, now we are done with the basic setup. Time for the good stuff; code! Go to your MainActivity and hit ⇧⌘A or CTRL+SHIFT+A to search for action names, and search for Convert Java File to Kotlin File, execute. This will convert your Java code to Kotlin. Please take a moment to look at the code, and see if you can understand the syntax. I hope it makes a bit of sense, at least it shouldn't look like mumbo jumbo to you. You could take a look at the local history of the file, you'll notice the following:

final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
val toolbar = findViewById(R.id.toolbar) as Toolbar  
  1. First you can notice that the final variable toolbar has no type indication in Kotlin. Kotlin can infer the type, autocompletion will continue to work, the variable is type safe.
  2. Next, the val keyword is like final, it is the keyword to indicate that it's a value; unmutable.
  3. Lastly casting is done by the as keyword. findViewById knows not about types, we need to cast it. In bullitt one I mentioned type inferring... This casting seems a bit like cheating, but that out of our hands for now. If findViewById would return something typed, it would automatically be inferred.
  4. There is no ;

Four lines down the next interesting thing awaits:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);  
fab.setOnClickListener(new View.OnClickListener() {  
    @Override
    public void onClick(View view) {
        /* Snackbar code */
    }
});
val fab = findViewById(R.id.fab) as FloatingActionButton  
fab.setOnClickListener { view -> /* Snackbar code */}
// Extracted Snackbar code for readability
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show()  
  1. See the amount of lines needed in Java vs Kotlin? I manually numbered them for you, for added drama. This is not only present in OnClickListener, this happens throughout your entire Java source.
  2. The second line in the Kotlin code shows the use of a lambda. Instead of using anonymous inner classes we can use lambda's. If you would choose not to use any reference in the lambda from your class, the lambda will not hold any reference to your class. It's a non capturing anonymous inner class. So no worries of leaking your Activity.
  3. If the last type of a functions signature is a lambda, it is the convention to move the closing bracket before the curly braces. In this case there is nothing left to use the the brackets for, so we can leave them out completely.

Less optimal example:

// The brackets should have been omitted
val fab = findViewById(R.id.fab) as FloatingActionButton  
fab.setOnClickListener ({ view -> /* Snackbar code */ })  

Now for a even more optimal example:

import kotlinx.android.synthetic.main.activity_main.*

fab.setOnClickListener { Snackbar.make(it, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show() }  
  1. The snackbar code is back in, this is necessary to show the usage of it. If a lambda only has 1 parameter, we do not need to declare it explicitly, instead we can just use it. Cool huh?
  2. The findViewById is gone, instead there is an include. synthetic knows how to generate code that finds the views in your layout file. We just include the correct layout file, activity_main in our case. Now we can just refer to the id's from the layout file, as if they are val defined in our activity (or fragment or view). This is why we added the additional classpath previously ;)

Last thing in this file to look at are function definitions:

 override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == R.id.action_settings) {
        return true
    }
    return super.onOptionsItemSelected(item)
}
  1. Overrides are part of the signature, not just an annotation.
  2. fun is the keyword to depict something as a function.
  3. The return type is at the end, behind the :.
  4. Something similar for the parameters; first the name, then the type.
  5. If statements, calling super and returning values are as you know it.
  6. When a method has noting to return we can omit the return type. However, you are allowed to say it returns Unit (which is like a fancy void keyword).

As a final note, here an example mutable variable:

var clickCount = 0;  
fab.setOnClickListener {  
  Snackbar.make(it, 
  "Clicked ${++clickCount} times",
  Snackbar.LENGTH_LONG).setAction("Action", null).show()
} // The SnackBar line has been broken up for readability on the web
  1. Where val denotes immutable values, var is the keyword vor mutable values. Again, the type is inferred.
  2. Line 4 shows string interpolation. Instead of string plussing, or StringBuilders, you can use ${XXX} in your string. XXX can in this case be a val, var, or fun, it just gets executed.
  3. This example has no Java counterpart. In Java the clickCount either had to be declared final, which would prohibit the mutability. Or it had to be declared as a field, which broadens the scope of the variable.

Ship it

At this time your source code has been infused with Kotlin, it is functional equal to what you had, and perhaps you learned something already. The next part will dive deep into the cool stuff. Writing Kotlin code, null safety, function extension, higher order functions and many many more things.

References

If you want to read more, have other views, and find more interesting content:

The Kotlin official docs
This is the source of truth for everything Kotlin. Pay special attention to the Learn tab. The documentation is very explicit, and a great way to continue learning.

Advancing Development with the Kotlin Language @ DroidCon UK 2015
At DroidCon UK Jake Wharton gave a talk about Kotlin. It was my first encounter with Kotlin, and have been hooked ever since. He does an amazing job explaining it, so I very much recommend you to watch it.

Kotlin: A New Hope in a Java 6 Wasteland @ DroidCon New York 2015
In this talk Michael Prado explains many things about Kotlin, amongst which a story about the progress of Java versions on Android.

Fragmented podcast with Hadi Hariri from Jetbrains
Fragmented is a podcast targeting Android developers. In this episode Hadi Hariri talks about Kotlin. He has been working at JetBrains for quite a while on this project, and reveals many insights about the why behind Kotlin.

My Github example
My github contains a repo about Kotlin. It contains a slide deck explaining Kotlin, and an example project similar as examples used throughout this post.