Defined by JetBrains guys, its creators, as:

Statically typed programming language for modern multiplatform applications

Kotlin is the new official Android development language, it was unveiled on July 2011, officially adopted by Google on the Google I/O 2017 and it was included on Android Studio since the version 3.0.

… Kotlin is expressive, concise, extensible, powerful, and a joy to read and write.

Created with the idea of eliminate the boilerplate code, it includes a bunch of new features to accomplish this goal. The idea is simple: Do more with less code. But more than this, the main goal of Kotlin, and all modern programming languages (Swift, Go, etc), is to have better code. And when we say “Better code” we are also talking about aspects of the safety, besides others, which allows the programmers to reduce the bugs and whole categories of errors as we will see through the article. Let’s see how Kotlin can become your Android apps development into a new, beautiful and sweet experience

Awesome new features

Auto-biding views

Have you ever you Butterknife or findViewById to get references to your views from the activity or fragment?. If so, you don’t need to take of this anymore. Consider the following layout called activity_main.xml

To use any view on the corresponding activity/fragment, you only have to import the layout, let’s see how:

Type Inference

Let’s see the following code

At least you don’t initialize the variable at the moment you declare it, you don’t need to explicity declare the data type, Kotlin can infere it. In the case of last variable of the example, the compiler will show a warning saying: “Explicitly given type is redundant here” so you can remove the data type at the declaration. As side note, var reserved word represents a mutable variable while val represents an inmutable variable

Null Safety

Have ever have a headache trying to find the cause of a NullPointerException error? Fortunately Kotlin introduce null-check at compilation time; which don’t allow you to run code without an initialization since by default all properties and variables on Kotlin are considered not-null (unable to hold a null value), at least you explicitly declared it null. Let’s analize the following declarations:

With a question mark we indicate to the compiler that the variable is able to keep null values. In this way, each time we want to use a variable that can hold null values we have to add a question mark to the statement to indicate to the compiler that the operation on this variable have to be execute only if the variable is not null. Let’s see an example:

In the above sample code, the first time lengthis called it will be executed since stringVariable is not null, however the second call of length won’t be executed by the compiler due to the stringVariable became null. “?:” is called Elvis Operator, it works in conjunction with null checker, in the example we are indicating return 10 if stringVariableis null and length can’t be execute. On this way, the nullPointerException is not a problem anymore.

Lambda Expressions

The normal way to declare a onClickListener on Android using Java is as follow:

Kotlin allows us to use Lambda expressions, also knows as anonymous functions, to do the same but without too much unnecesary code

Lambda Functions are especially good to work with collections. Imagine you need to go through a list of number and get the add up of all of them, to perform that action you just need a line of code

Also, you can store a lambda function into a variable and then use it or pass it as a parameter of another function

Extension functions

Extensions functions allow you to add new funcionality to existing classes, without modify the original declaration of the class or extend it. This is very useful when you want to add new behaviour to third party or framework classes that don’t allow you to modify them. For instance:

On the example above we are extending the ArrayList class by adding a new function called average(). Now we can use it as any other function of the ArrayList class; this also can be apply to classes created by us. An important detail to keep in mind is that to use an extension outside its declaring package, we need to import it at the call site. Let’s see how to use the extension function created:

with() Function

Consider the following sample class

If you need to interact with the class, its properties and method, you can do it without type the name of the variable followed by a period, as follow:

High Order Functions

High Order Functions are those that accept functions as parameters and also allow us return a function. Let’s see an example

In the above example we are saying that checkoutOrder function will receive a function called actionToExecute as a parameter, actionToExecute have to be a function that receives two ints as parameter and doesn’t return nothing. To use this function we can do something like:

Data class

Plain Old Java Object or POJO are commonly use on Android to represent business objects, they are classes that only contain properties, its getter and setter methods, besides other methods like: equals(), toString(), hasCode(), etc. With Kotlin you can create a POJO, its constructor, getter, setter methods and the others helper methods with only one line of code.

In the above example we are creating a POJO called Book which has three mutable properties: title, author, year; the helper methods: equals(), toString(), hasCode(), getters and setters and constructor are autogenerated by Kotlin.

Kotlin notes:

  • As maybe you already noticed, it isn’t necessary to write semicolon at the end of the line to indicate the end of the statement.
  • By default everything (variables, constants, functions, classes, etc.) has a public scope.
  • Var is a reserved word that represents a mutable variable while val indicate an immutable variable.
  • Properties on Kotlin must be assigned when declared or in a constructor, at least you declared them as lateinit or add a question mark to allow them keep null values.
  • In Kotlin everything extends from Any as in Java everything extends from Object and there are not primitive types.
  • By default, classes are final so in order to extend a class it has to be declared as open or abstract.
  • Unit is the default return value for functions, it is similar to Void in Java.
  • The arguments of the function can have defaults values.
  • When calling a function the name of the argument can be used to improve the readability of the code.
  • If for some crazy reason you want a NullPointerException thrown the same way as in Java, you can use !! operator.
  • To perform a cast you have to use the keyword as, but whether you want a “safe” cast with a null validation you can use as? which will return null is the casting is not valid.
  • A big difference with Java is the == and != behaves different, in Koltin == and != validate is the value of the properties of two instances are the same, but if you want to compare if the instances of an object are the same (identity check) you need to use === and !==

Conclusion

Kotlin was created thinking in the developer, providing a more concise, intuitive and readable syntax and allowing the developers create more significant functionality with less code. It’s still a young programming language, but due to it was already officially adopted by Google, it will start to grow from now

A final comment, a crucial thing to mention is that all aspects of a new language has a place and should not be abused. For instance, the ability to make things more concise should not give the developer license to make things so cryptic as to be unreadable by fellow programmers. Just because one CAN do that now does not mean one should :)

--

--