What has Kotlin?


Without diving too deep in Kotlin languag, these are some interesting features we miss in Java:


  • Expresiveness 
With Kotlin, it’s much easier to avoid boilerplate because most common situations are covered by default in the language. For instance, in Java, if we want to create a data class, we’ll need to write (or at least generate) this code:

With Kotlin, you just need to make use of a data class:

This data class auto-generates all the fields and property accessors, as well as some useful methods such as toString().

  • Null Safety 

When we develop using Java, a big part of our code is defensive. We need to check continuously whether something is null before using it if we don’t want to find unexpected NullPointerException. Kotlin, as many other modern languages, is null safe because we need to explicitly specify if an object can be null by using the safe call operator (written ?). We can do things like this: 



  • Extension functions 

We can add new functions to any class. It’s a much more readable substitute to the usual utility classes we all have in our projects. We could, for instance, add a new method to fragments to show a toast:


  • Functional support (Lambdas) 
What if, instead of having to implement an anonymous class every time we need to implement a click listener, we could just define what we want to do? We can indeed. This (and many more interesting things) is what we get thanks to lambdas:



This is only a small selection of what Kotlin can do to simplify your code. Now that you know some of the many interesting features of the language, you may decide this is not for you. If you continue, we’ll start with the practice right away in the next chapter


Comments

Popular Posts