Kotlin is the new open-source programming language supported by Google for Android applications (but also for the Java backend and JavaScript engines of web browsers). It aims to improve the productivity of developers while remaining compatible with the existing code. It is also possible to compile it natively.

Prerequisites

Android Studio 3 includes by default the tool support for Kotlin; it is available in stable version since October 2017.

This article is primarily intended for people with some notions in Android application development.

Introduction

The creator of Kotlin is none other than JetBrains, the editor of the IntelliJ IDEA IDE that serves as a base for Android Studio (our favorite IDE for developing Android applications). The language got created in 2011, but it was only in May 2017 during the Google I / O conference that Google officially announces its support. Kotlin is now on the front of the stage.

It is an object-oriented and functional programming language that can also be called a multi-paradigm language just like Scala or Python for example.

It has the advantage of being interoperable with Java code because Kotlin is compiled into bytecode for the JVM, but it is exceptionally well thought out at the syntactic level since any Java class can be manipulated directly in Kotlin. It is indeed possible to have Java and Kotlin code within the same project, but also to convert a Java project into Kotlin.

Forward!

Google Developers provides a number of Kotlin tutorials on its codelabs.developers.google.com site , two of which are “Build Your First Android App in Kotlin” and “Taking Advantage of Kotlin”. I advise you to put them into practice because they allow to understand the advantages of Kotlin compared to Java, raise awareness on good practices and offer tips.

To perfect your Kotlin syntax, you can train on kotlinlang.org or Android Studio with the EduTools plugin. These are the same exercises but one is on browser and the other on Android Studio.

1. Discovery

This is a detail that may be important, Kotlin files have the suffix .kt and no longer .java

  • val and var
    The key word  allows, as in Java, to declare a re-assignable variable.

The keyword val makes the final assignment as final Java.

  • data The keyword data tells the compiler that the class is used to represent an entity. But it also generates a number of useful methods like the methods toString(), copy(), equals(), hashCode() or unstructured statements of such object.

Example:

A deconstructed declaration generates several variables at a time. We have declared two new variables: name and age that we can use independently.

  • StringKotlin includes support for String that allows the use of templates within the String.

2. Null Safety

Ah, this famous NullPointerException that we love so much (or not). With Kotlin, it is now possible and easy to reduce this number of errors. All variables are nonzero by default, but it is possible to call the exception with throw NullPointerException().

This variable does not accept null, so this line will not compile.

If you want to accept null, you must add one

with your type

  • The Safe Call Operator (?.)If you try to compile this line and x is null, you may have problems compiling.

To avoid adding a condition if(x != null), it is possible to add ? that informs that x can be null. If this is the case, the method toDouble() will not be executed and will return a null. The variable y will then be of type Double?

If you need to execute a number of statements when the value of the object is other than null, you can use the Safe Call operator ?. followed by let.

  • The Elvis (? 🙂Elvis operator allows you to not return a null value if, as in the previous example, you have the possibility to obtain a null result.

Elvis is therefore composed of ?: and allows to assign a value to the result if it is null.

  • The operator !! It will avoid checking that your variable is null. It is, therefore, possible to obtain a NullPointerException in this case.
  • lateinit The keyword lateinitis used when we know that the variable will not be null (with the exception of a boolean) when it is used, but that it is not possible to initialize it during its declaration. lateinit allows circumventing the blocking produced by Null Safety set up in Kotlin.

3. Kotlin Android Extensions

The main advantage of Kotlin Android Extensions is to dispense with the declaration of the different views (TextView, Button …) that we see in the Java code. To do this, you can import the plugin Kotlin-Android-extensions.

Adding the kotlin-android-extensions plugin

If you want to use a graphical component from an XML file, you must declare it with findViewById when you code in Java.

A first improvement had been implemented for Java with the use of AndroidAnnotations. @ViewById made the connection between the view and the variable at the time of its declaration in the class.

Java – AndroidAnnotations

Thanks to the plugin Kotlin-Android-Extensions, it is possible to reduce the number of lines and to increase the legibility of the code by using the component directly with its Id. The method will be replaced by an import ImportViewById. It is no longer necessary to declare a variable when you want to use a view.

Xml file

Kotlin without Kotlin Android Extensions

Kotlin with Kotlin Android Extensions

The documentation is available here .

4. The lambdas

A lambda is an expression to describe an anonymous function defined by input parameters and a return type. It is surrounded by {} and -> separates the parameters of the function from its definition.

Example:

Parameters: x: Int, y: Int
The definition: x + y

Scenario Instead of creating a function to say Hello World, we will use a lambda expression.

For a parameter

For several parameters

When a lambda expression has only one parameter, we can use the keyword it as in the example below.

Lambdas are very handy when it comes to lightening the code as for the method setOnClickListener().

Let’s see how it is on Java:

And on Kotlin:

  • Kotlin Standard Library The lambdas can also be passed as a parameter of functions from the Kotlin library like sortBy(), map(){} or mapTo(){}

Example with sortBy() to sort an array.

5. Extension functions

Kotlin supports extension functions and extension properties, which provides the ability to extend a class with new features without having to inherit from the class.

It is advisable to create a new file in Extensions.kt order to place all the extensions.

Here we have an extension of an object EditText we named validateWith that displays an image to the left of the component. It will be different if the entry is valid or not.

The documentation of the extension functions is available here.

6. Classes of objects are lighter

In Java, the class of an object can be relatively large with the generation of one or more constructors as well as getters and setters.

The Kotlin syntax does not require us to code them, they are optional, which makes the class more readable.

Java – Contact Class

Java – Change or recover the email

Let’s see how concise it can be in Kotlin

Kotlin – Contact Class

Kotlin – Change or recover the email

7. Interfaces

Kotlin’s interfaces are very similar to Java. They can contain abstract method declarations, as well as method implementations.

Unlike abstract classes, interfaces can not store the state. They may have properties but these must be abstract or provide accessor implementations.

Kotlin

Console output

8. ConstraintLayout

The arrival of Kotlin sign the use (recommended) of Android Studio 3 and therefore of ConstraintLayout.

This allows you to create complex layouts without nesting groups of views into each other. This is quite similar to RelativeLayout because views are organized based on the relationship between neighboring views and the parent layout. Because ConstraintLayout is more flexible than RelativeLayout, it is also easier to use thanks to the Android Studio layout editor.

Example:

LinearLayout
ConstraintLayout (we can see the relations between the views)

You can find out more about ConstraintLayout on the Android Developers site.

Convert Java code to Kotlin

The Codelabs “Taking advantage of Kotlin” tutorial allows you to convert your Java code into Kotlin while being guided with explanations and tips.

It’s easy to convert a file. In Android Studio, open the file you want to convert, and then perform the following action.

Code> Convert Java File to Kotlin File

It’s magic, and your Java code has become Kotlin code. Once converted, you must, of course, take a look at it to make the specific optimizations to the Kotlin language. Even a simple copy/paste from a Java class to Kotlin will automatically convert your code.

Tooltips are there to help you, so do not hesitate to watch what they offer.

In the case above, the help proposes to simplify the loop for with the mapTo() Kotlin Standard Library function. This method allows, in our example, to simplify the backup of the list of Contact.

With the usage of the loop for:

With the function mapTo()

Conclusion

Kotlin helps clarify and lighten the code, and thus improve the maintainability, or even increase the velocity of developers. It aims to avoid the limitations of the Java language by putting in place various devices that make life easier for developers. We note in particular the disappearance of the NullPointerException, the type inference, the unstructured declarations, the extensions functions …

The migration of Android applications (native) from Java to Kotlin will be able to be done smoothly thanks to the compatibility of the two languages ​​and the possibility of a file conversion.

Many open source projects and libraries are available here .

sources