Kotlin for Android was a bit slow to pick up but with the full support from Google has made it to the top of countless “top languages to learn next” lists.

But is it really the future of Android development and or just another overhyped tech?

What is Kotlin and why should you care?

Kotlin is a general-purpose statically-typed programming language for Java Virtual Machine (JVM). The language is compiled in Java 6/8 bytecode, but can also be compiled into JavaScript and into native code.

The creators wanted to make a tool that would allow developers to build all the components of a modern application using a single language. This includes full-stack web applications, mobile clients for iOS/Android, IoT embedded platforms, etc.

Kotlin was born in 2010 as an internal project at JetBrains, the company best known for its IntelliJ IDEA integrated development environment.

The majority of developers at JetBrains were involved in Java projects (over 70% of company’s output).

Java is a tried and true language but has archaic features. It requires you to manually do a lot of things that other languages do all by themselves.
For example, to print the phrase “Hello World” in Java, you’d have to write three lines of code.

In some of the newer languages, like Swift, the same task takes just three words.

More lines of code also means more potential bugs and a product that is more likely to crash.

The guys at JetBrains have looked into Java alternatives but the need to maintain and support numerous Java apps has stopped the company from opting other languages. They still needed interoperability with Java.

In 2011 the developers revealed Kotlin to the public. A year later, the project went open-source.

Since then, the Kotlin team at JetBrains has grown to 40+ developers and its GitHub repository has almost 200 contributors.

In 2017, Google made Kotlin an officially supported language for Android.

The language promises Android developers their favorite Java features together with several quality of life improvements:

  • Less boilerplate code
  • Increased readability
  • Full interoperability with Java
  • Data classes
  • Support for both OOP and the functional paradigm
  • A convenient standard library
  • Small file size (adds around 100KB to Android apps)

So let’s dig deeper and discover whether Kotlin has achieved those noble goals.

Kotlin Syntax

The syntax of Kotlin should be familiar to every developer accustomed to the OOP paradigm. Despite a few differences from Java, like the modified constructor or the declaration of val var variables, the syntax should be clear even to the newcomers.

The function that receives two Int type parameters and returns an Int type value:

Kotlin Syntax

Read-only variable:

Kotlin Syntax

Variable:

Kotlin Syntax

SomeClass class that is a SomeAbstractClass descendant and implements the SomeInterface interface:

Kotlin Syntax

Interoperability with Java

You can continue working on your old Java project using Kotlin. All your favorite Java frameworks will be also available in Kotlin.

The classes written in Kotlin language can be used in Java and vice versa.

Interoperability of Kotlin with Java

Note: in Kotlin, the class properties are always available via fields and not via methods.

Kotlin Data Classes

In Kotlin, Data Class contains automatically generated getters, setters, toString(), copy(), hashCode(), equals(). But when compared to Java, it’s much more compact.

Java:

Java Data Classes

Kotlin:

Kotlin Data classes

IDE enables generating toString, equals, hashcode. Although when you add, remove, or change one of the class fields, you have to generate these methods again.

Extension Functions

Remember the first time when you had to sort List in Java? You didn’t find the sort() function and had to learn Collections.sort(). Later when you had to change all the letters to lowercase, you had to write your own helper function because you didn’t know about StringUtils.capitalize().

If there was a way to add new functions to the old classes, your IDE could find the correct function while completing the code. This is exactly what you can do in Kotlin:

Kotlin extension functions

Kotlin enables you to add a method to a class without creating descendants.

Android SDK:

Kotlin extension functions

Add some Kotlin magic:

Wrapping the third-party API.

As an example, the View tree processing (Android SDK):

Java:

Kotlin:

Null Safety

Java should be called almost statically-typed programming language. Here the type String variable doesn’t necessary refer to String. It can also refer to null. Despite being the usual practice, this decreases the safety of static type checking. As the result, Java developers have to live in the constant fear of Null Pointer Exceptions (NPE).

Kotlin solves this problem by dividing the types into nullable and non-null. Each reference should be explicitly declared as nullable or non-null. The types are Non-null by default, but you can transform them into Nullable by adding ?:

The safe ?. calls return the result of a function execution or null if called to null.

The Elvis operator returns the value to the left of the operator if the value isn’t null or to the right if it’s null.

Null Safety examples:

Java


Kotlin

Control Flow

If is an expression. It returns a value:

When is the replacement of switch from Java and can also return a value. Receives an optional parameter.

There is no ternary operator in Kotlin because if returns a value.

Functions

Lambda is an anonymous function written in curly brackets, the parameters are listed before the -> symbol.

Java 7

Kotlin

A higher-order function is a function that receives other function as an argument or returns a function.

The lambda system is an ideal balance between the readability and succinctness due to several smart solutions:

  1. You can move or omit the parentheses in a method if the lambda is placed last or is the only argument to the method;
  2. When a function literal contains a single parameter, you don’t have declare it and can also skip the -> symbol. In this case the parameter’s name will be: ints.map { it * 2 }.

The system of lambdas together with the extension functions makes Kotlin the perfect tool for building Domain-Specific Languages (DSL). Anko is an example of DSL made to expand the capabilities of Android development:

Using lambdas has its own drawbacks.

Every lambda is an object that has an access to the fields of the external object. This adds an additional overhead and can cause memory leaks. You can avoid this by embedding the lambda code instead of creating an object.

This is what the inline operator is for.

The parameters of a function can receive the default values. You can declare the name of parameters while passing the arguments.

When using the named parameters, you can change their order.

Delegation

Kotlin has an inbuilt support for the Delegation pattern.

You can also delegate an object’s field to the other class which gives its own implementation of get() and set() methods.

Delegated Properties:

Lazy delegate:
fun <T> lazy(initializer: () -> T): Lazy<T> (source)

Executes the initializer during the first access and returns the result.

The result is:
computed!
Hello
Hello

Smart casts

After checking the object’s type, you don’t have to make an explicit cast.

Java:

Kotlin:

Collections

Kotlin collections API is a Java collections wrapper. Kotlin explicitly differentiates mutable and immutable collections.

The collections have the convenient inbuilt ultis functions such as first(), last(), filter(), sort(), zip(), etc.

The standard library

The standard library also has a few useful functions that can be applied to the objects of any type.

Let: calls the specified function block with this value as its argument and returns its result.

Apply: calls the specified function block with this value as its receiver and returns this value.

What difficulties to expect when migrating from Java to Kotlin?

  • The loss of git history during the file conversion.
  • Less information available on the Internet when compared to Java.
    • StackOverflow:
      Java ~ 1,300,000 questions;
      Kotlin ~ 5,000 questions;
    • Fewer forum threads;
    • Fewer open-source projects:
      GitHub Java ~ 1,000,000;
      GitHub Kotlin ~ 2,000;
    • Fewer books.
  • Project build slowdown under certain circumstances:

Estimated build time with the clean build folders.

Clean project:
Java ~ 25 sec.
Kotlin ~ 27 sec.

+ Dagger 2 + Data binding:
Java: 42 sec., 29 sec., 26 sec.
Kotlin: 55 sec., 33 sec., 32 sec.

  • Null safety violation when using Java and Kotlin together.

Conclusions

So, what language to learn if you’re new to Android development?

My answer is: start with Java and then learn Kotlin.

Kotlin is a wonderful new language that has a bright future ahead of it. But for now, it’s almost impossible to find a job as an Android developer without a good grasp of Java.

The abundance of Java documentation and resources will make learning it easier. Java is one of the most popular programming languages in the world and for the foreseeable future, it’s here to stay.

As you’ve seen, Android development with Kotlin features several quality of life improvements, but due to their similarities, learning Kotlin after Java is a piece of cake!

But what if you’re an experienced Android developer and want to switch from Java to Kotlin?

On the one hand, you’ll get a new language with a lot of exciting features, but on the other, you’ll suffer from the problems of young languages – such as relatively small community, or a bit slower build time.

And don’t forget about Java-Kotlin interoperability – you can try Kotlin for a small part of your project, then decide if you want to use it more widely.

So, what’s your take on Kotlin? Do you believe it’ll be a success? Will you learn the language or stick to Java? Share your thoughts in the comments.

  •  
    16
    Shares
  • 9
  • 2
  • 5
  •