- SOLD IN 30 MINUTES | THE OTHER 15 MINUTES -

Cool, you're back... well I assume you just finished Part 1 of this two parter. If the answer is no, then either you are already a bit familiar with Kotlin, or you just want to see the cool stuff, or you have some type of secret other reason which you may share in the comments.

We will be picking up where we left off, we had a template Android project, which we infused with Kotlin and we did a bit of Kotlin reading. Next to that we already had a quick look at String interpolation, so we did write some code already.

The Cool Stuff

There is a lot of cool stuff to cover. Actually it's still a subset of the cool stuff, but showing everything is a bit too much. It's the art of leaving things out, to focus more on the things that matter. You can always have a look at everything, and then compose your own list of your favorite picks. Let me know when you do, but until then, here are mine ;)

The Constructor

Things have to come from somewhere, and for classes the first light of day is during construction. The constructor should be used to store things in fields that are passed as parameters. In rare cases you might need to init or collect some other resources. So if storing things in fields is the number one function of a constructor, why does it have to look like this?

public class SomeJavaClass {  
    private FloatingActionButton fab;

    public SomeJavaClass(final FloatingActionButton fab) {
        this.fab = fab;
    }
}

How cool if it were to look like this?

class MyFirstKotlin(private val fab: FloatingActionButton) {  
}

The signature of class's constructor is in the same place as where the class is defined. Assigning things to fields can be directly done in the definition. Because the keyword val (or var if it had to be mutable) is in the definition, it is automatically assigned to a field. If a keyword is omitted it will not be stored as a field, but it can still be used in other field assignments, or a init block. After construction time, the parameter is no longer available.

class MyFirstKotlin(fab: FloatingActionButton) {  
    var fabId = fab.id

    init {
        Log.v("KotlinFTW", "I've got me a $fab")
    }
}

There is also no need for getters and setters, you can just use the properties. This is a big no-no for Java, since encapsulation is totally broken if you do that. But similarly like for example C# we can do like below. We can still create custom implementation for getters, and setters, and change modifiers.

var isFabVisible: Boolean = false  
    get() {
        return fab.visibility == View.VISIBLE
    }
    private set 

The last thing I'm going to mention about construction are data classes. If you are in need for a simple data class, where you just want a big ass constructor for all your data, and a bunch of properties, the following one-liner is here to help you. As a kicker let me tell you that these things play well with for example Gson. Everything compile straight down to bytecode, so Gson knows how to work with Kotlin classes.

data class MyDataClass(var anInt : Int, val aString : String, val aComplexObject :  MyFirstKotlin)  

Null Safety

I am not gonna quote that one guy, but sometimes nulls are bit annoying. They are all over the place, people love em... Don't know what value to give something? Too lazy to make a null object? Perhaps a different callback then? Also no? Well.. In that case, here's your null reference. The problem is not that things can be null. The problem is that we expect things to be non-null. That's when the magic happens. Let me quote myself on that one, it makes for a fancy graphic.

Null references have never killed anyone.
Suddenly invoking methods, that's what gets you, that's the killer.

David Hardy

What solutions do we have? We can annotate things with @NonNull, or we can null check everytime. We can get defensive to a level where more lines are spend on null checking, than actual business logic. But the problem is not that something is null, it's the blind invoking that is the problem. Lets see some Kotlin, which I just added to the onCreate method of our MainActvity. For this example I reworked the constructor example from earlier, to pass in the fab via a method instead, which makes the examples more clear:

val myFirstKotlin = MyFirstKotlin();  
myFirstKotlin.doMagic(fab)  

Ok, so what do we see? We see first some assignment. We new something without a new keyword, since it is a redundant keyword which is redundant. The mere fact that it is preceded by the = sign already indicates we want a new object. Next we invoke a method.
This is also pretty straight forward in Java. If myFirstKotlin would be null, your IDE will already start to shout at you.

fun doMagic(fab: FloatingActionButton) {  
    fab.setOnClickListener { /* Snackbar code */ }
}

This is already a bit more tricky in Java, since fab is passed in, the IDE cannot determine if it could be null. In Kotlin however it is guaranteed to be non-null. How you ask? Well by definition. Let's have a look at the definition is something can be null:

fun doMagic(fab: FloatingActionButton?) {  
    fab?.setOnClickListener { /* Snackbar code */ } ?: Log.v("KotlinFTW", "You didn't fool me!")
}

We're not really sure if it is non-null, so let's ask. How would you ask in real live, you make a bold statement and add a question mark to the end of your sentence (kinda), the same holds here. By adding ? we indicate that it might be null, so don't blindly invoke a method, but do a check. The IDE will already tell you that fab.setOnClickListener() is illegal. You must do a check! So instead of ., you do ?.. The method will only be called if fab is non-null. Optionally you can use the Elvis operator ?:, which allows you to execute some code if fab is null. Now that's safety first!

Elvis operator based on emoticon

One more neat trick:

if (fab != null) {  
    fab.setOnClickListener { /* Snackbar code */ }
}

In this case it's just for the example, but there are moments that you want to do a manual check. But still there is an improvement obtained. By merely doing the null check, Kotlin can do a smart cast and guarantee non-nullness, so you do not need ?. in the if scope. The same holds for below example

if (fab == null) {  
    return
}
fab.setOnClickListener { /* Snackbar code */ }  

Smart Casts

Class casting isn't something to be proud of. Often you could change the architecture so that you can avoid casting, but not always. Especially when dealing with foreign APIs. So lets optimize it! Back to our doMagic method:

fun doMagic(fab: Any?) {  
    if (fab is View) {
        fab.setOnClickListener { /* SnackBar code */ }
    }
}

Any is like the Java Object, it indicates that it can be Any object. The second line is more interesting, this is where the cool stuff is. If fab is of type View, then within the if scope it is automagically casted to View. Mind the fact that null is not of type View, so the null check is implicit!

Function Extensions

Has that /* Snackbar code */ thing been bothering you. Haven't you wondered, why, why, why not extract it into a function? Well, my fingertips did it many times during the course of the writing process. But I reverted, and reverted again, just to make a point. That piece of code is messy, it is. Take a look at it:

Snackbar.make(it, "It's messy man.. where to begin?", Snackbar.LENGTH_LONG).setAction("Action", null).show()  

It's static method chaining, requiring 75 characters exluding the message, that's verbose and clutter for you! Lets improve.
First do the sensible thing and extract the message, then extract the Snackbar code:

val message = "It's messy man.. where to begin?"

private fun showSnackbar(it: View, message: String) {  
    Snackbar.make(it, message, Snackbar.LENGTH_LONG).setAction("Action", null).show()
}

Now for the cool part, the one function to rule them all. From henceforth you will never need to write it ever again (in this project). You'll need to do the following outside of any class scope, best to make a new file called Extensions.kt or something alike.

fun View.showSnackbar(message: String) {  
    Snackbar.make(this, message, Snackbar.LENGTH_LONG).setAction("Action", null).show()
}

Hang on a sec, I'll show you the thing we just created in use!

fab.showSnackbar(message)  

That's it! fab.showSnackbar(message) is everything you need to do now to show a Snackbar! Isn't that just amazing? Or perhaps a bit of magic? Let me explain.
The showSnackbar method (which best should be in a separate file) is outside of any class scope. The method name is prepended with View., this indicates that the following method should be added to the interface of the object itself. So the method showSnackbar is now available on any View. The body of the method acts as if it is part of the View class, but it can only access things that are publicly visible. This means you cannot add new fields, but you can make use of any API that belongs to that object. That means that this refers to the instance of the View that this method is invoked upon. You can do this to any class, no matter if it is open, closed, final, virtual or transgender. Epic.

Kotlin function extension is epic

Do you even realize the unlocked power?

Kotlin comes bearing extension function gifts, with inlining

How often did you type the following (or let your IDE create this boilerplate for you):

for (final Object object : objects) {  
     ...   
}

How about the following:

objects.forEach { ... }  

Kotlin function extension feels smooth

But it gets better, there are many, many of these things build in the language; map, flatMap, reduce, first, last, count, isEmpty, isNotEmpty, reverse, slice, sort, the list continues and continues. But wait, there is more! Lets look at forEach:

public inline fun <T> Array<out T>.forEach(action: (T) -> Unit): Unit {  
    for (element in this) action(element)
}

Forget for a sec the out and -> thing (and also Unit, which is a fancy word for void), we will come to that. But do have a look at the second keyword; inline. The compiler will inline the body of this method into the calling code, thus not constructing an anonymous (static) inner class, but it will add the boiler plate straight into your class file! Performance much?

Also, do not forget about readability. In Java you could achieve something similar with static helper methods. For example traversing a list, doing some mapping, filtering and printing. In Kotlin it would look exactly like this:

listOf(1, 2, 3, 4)           // list of 1, 2, 3, 4  
    .map { it * 10 }         // maps to to 10, 20, 30, 40
    .filter { it > 20 }      // filters out 30, 40
    .forEach { print(it) }   // prints 30, 40

In (Pseudo) Java, with static includes, operations directly on a list would look something like this:

forEach(  
    filter(
        map(
            Arrays.asList(1, 2, 3, 4),
            i -> i * 10),
        i -> i > 20),
    i -> print(i));

Now which of these two is more readable? Also, the Java example need 3 anonymous inner classes (SAM types). You could resort to explicitly making things streams, but still the SAM types are there. Kotlin operates just on the list, without any object instantiation overhead, perfectly readable.

Higher Order Functions

Ever heard someone say 'Treat your functions as first class citizens'? Ever understood what it ment? This phrase has become more popular overtime, but the meaning is far less complex than what people think they are saying. Basically it boils down to being able to pass a function into methods, or saving them as fields. Treat a fun the same way you would treat a val or var. Actually we've been doing this for quite some time already over the course of this post, since lambda's are the prime example of higher order functions in use. Let's take another look at the forEach example.

public inline fun <T> Array<out T>.forEach(action: (T) -> Unit): Unit {  
    for (element in this) action(element)
}

What kind of parameter is action? It's something of type T which converts to Unit. Unit is like void, it indicated that there is no return value. So it means we provide it with something of type T and it does something with it, we do not care what. We can call action with any element, by just calling action(element). But what about the onClickListener of the fab? When interoperating with Java code, if an interface that we need to implement only has 1 method, we do not need to explicitly implement that interface. Instead we can make a lambda, which will implement that one callback. This holds for any interface with at most one method, regardless of the number of parameters. Let's try to make a higher order function ourselves!

fun View.showSnackbar(x: Int, y: Int, action: (Int, Int) -> String) {  
    Snackbar.make(this, action(x, y), Snackbar.LENGTH_LONG).setAction("Action", null).show()
}

So now we have a new method on each view which takes two ints and higher order function, which takes two ints and returns a String. Let's try to use it!

fab.showSnackbar(1, 2) { x, y -> "The sum of $x and $y is ${x + y}"}  

Since we now have a lambda that has 2 parameters, it cannot be used. We need to name the parameters, for which x and y are chosen, the types are inferred. After the -> we can create the function, for which we used String interpolation take make something out of it. It will return "The sum of 1 and 2 is 3".

To make the case for 'first class citizen' complete, let's see how defining functions as fields looks like. The behaviour is identical to the example above.

val firstClassCitizen: ((Int, Int) -> String) = {  
        x, y -> "The sum of $x and $y is ${x + y}"
    }

fab.showSnackbar(1, 2, firstClassCitizen)  

Conclusion

I hope you enjoyed my various outtakes, or high lights, of Kotlin. I think there are some very, very powerful possibilities available now, which just weren't there before. Sure, some of these things are not unique. Most of these things are not unique. Almost nothing of these things is unique perce. But it is the quality of the execution that one must admire. JetBrains has collected many of the powerful concepts of other languages out there, and have combined them in a recognisable way. It looks a lot like Java, it is intended that way; It is crafted that way. JetBrains has a unique position in the market that makes Kotlin a true challenger of all the other languages on the JVM (and soon also JavaScript). It's open source, it's free, there's no vendor lock. It executes at least as fast as Java, and outperforms Scala. It's 100% interoperable with Java, so you can call painlessly any Kotlin method from Java, and any Java method from Kotlin. You can use any Java library and mix it with Kotlin;, Gson, Dagger, RxJava and all the others will continue to work. Some, like RxJava, have a Kotlin version to create better suitable interfaces, but for the business logic RxKotlin relies on RxJava.

But to all you naysayers, I hear your question;

Isn't this all too good to be true. There has to be a catch, a trick, some smoke and mirrors somewhere?

Nope.
Not Really.
Maybe.
It’s Classified.
Ok... just minor things.

  1. The compile time is slightly slower than Java's compile time. It's on the todo list of JetBrains to boost it.
  2. All classes are closed by default, which can be a change in your testing methodology, but you can make them open if you want. In Java it's the other way around.
  3. It's still in Beta (version 1.0.0.x), awaiting official release in the near future. The plugin for IntelliJ can give some troubles every now and then, but nothing major.

To my knowledge this is it. This is the complete list of downsides. I hope they haven't scared you away, because I am using it in my daily work. I love it. I can recommend all Java developers to start using it, and I hope I've convinced some of you. If so, please let me know. If not so, then I would appreciate it if you can give me some insight into why not?

Kotlin is more rich than these outtakes, so if you just spend your 30 minutes and you are sold, be sure to check the references below. If you need more persuasion, do so to. If you're not sold by now, let's leave it at this, I hope you atleast enjoyed it.

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.