Kotlin - A Language we should know it exists

Vaclav Souhrada
7 min readMar 8, 2017

--

Kotlin is a programming language which is close to my heart. I knew that there is some language called Kotlin a few years ago but I really tried it ± one year ago and I have to say that I’m a very big fan of this language now. First I made the evaluation and mainly focused on interop. with the JavaScript. For my team, it was interesting if we can use Kotlin as a replacement of the JavaScript for the mobile hybrid development.

I was pleasantly surprised what everything Kotlin offers to developers and how we can make our code cleaner and speed up development.

My first interest with Kotlin was to evaluated this language and get knowledge how Kotlin could be useful for our development team.

Currently, we have Kotlin as the main programming language for microservices.

What is Kotlin

Kotlin is a pragmatic programming language for JVM, Android, JavaScript. It is an Open Source language created by the JetBrains.

  • Statically typed programming language targeting JVM and JavaScript
  • Focused on interoperability, safety, clarity and tooling support
  • Very easy for developers to use Kotlin — similar to Java/C#/JavaScript/Groovy
  • No semicolon required ;-)

Safety

  • Kotlin is null safe, which means that we deal with possible null situations in compile time, to prevent execution time exceptions
  • You need to explicitly specify if an object can be null (see top 10 features for details)

Functionality:

  • Kotlin is basically an object-oriented language, not a pure functional language.
  • It uses many concepts from functional programming’s, such as lambda expressions, to resolve some problems in a much easier way
  • Another nice feature is the way it deals with collections

Interoperability

  • You can continue using most libraries and code what you have already in Java because the interoperability between both languages is working very well without any troubles (at least I did not have any problem so far)
  • Of course, you can have both languages (Java & Kotlin or JavaScropt & Kotlin) in the same project

Extensibility

  • We can extend any class with new features event if we do not have access to the code of the class which we want to extend

Top 10 Features that I love on Kotlin

In Kotlin you can find a lot of features which you will love. I will mention top 10 features that I love.

1. Null Safety

Kotlin is null safety language:

In this example, address and telephone cannot be null — you will see an error at compile time if you want to set them null value:

You must explicitly say that a variable is nullable to be able to assign null to it. This is done via “?” after the variable type (see a variable email in the example above).

Your code can fail at compile-time whenever an NPE may be thrown at run-time:

To solve a compilation error of x.length we can use if-statement:

or we could do it in a better way via “safe calls in Kotlin” which returns the value of the call if the caller is not null, otherwise null is return.

Elvis Operator

You can work with nullable types more effectively by using the “Elvis Operator”.

In this case if x is not null a length will be used, otherwise -1 (default value).

2. Data Class

When you are creating business logic, persistent layer, …, -> you creating domain objects, classes that do nothing but hold data (POJOs)… For instance, we must create Customer class which holds data about customer’s id, name, and email.

In Java:

In Kotlin a class can be marked as data class:

The Kotlin compiler will do for us:

  • generate functions: hasCode() , equals() , toString()
  • add copy() function (see below more about this function)
  • componentN() functions

Copying

Sometimes you need to copy an object to a new one with some different values of our variables. This is what copy() function is for:

3. Extension Functions

Kotlin allows us to extend the functionality of existing classes without inheriting from them.

The functioncapitalize() is an extension function of theString class. Inside the extension function, you access the object on which it was called using the keyword "this".

Extensions do not modify classes they extend and are resolved statically.

Thanks to extensions function code in projects where I’m using Kotlin is much cleaner. I do not have xxUtils(.java) classes anymore.

Conversion to JSON could be a good example where we should use extension functions. We will show it on a very simple example that adds extension function to all “objects” in Kotlin. ( kotlin.Any and java.lang.Object are different types, but in runtime, they are represented with the same java.lang.Object class).

4. Smart Cast

This is one of my favorite feature which I really like and make my life easier.

How often have you already cast objects? How often was it actually redundant?

For example, if you want to check Object if it is an instance of java.lang.String if yes you want to print size of this text you have to first check type and then you must cast an object to String before you have access to specific String's methods. When I started with Kotlin so I did not consider this as something awesome, but after a few days I found this feature I really missing in Java.

The Kotlin compiler is a really smart when it comes to casting. It will handle all redundant casts for us.

The instance of Java operator in Kotlin is called is. In the example above you can see that in Kotlin you do not need to cast object inside of statement if you already checked it with an operator is. This redundant casts in Java I did not see as something strange until I began to use in Kotlin.

When expressions are another place where we can see smart casts:

Smart cast together with when expression makes code readable:

On example, above you can see how for instance we can check if the event which comes from event bus can be check and cast to correct java object. I agree that in this use-case it doesn’t look bad in java but in Kotlin you can have this code:

Maybe I’m wrong but from my point of view, Kotlin is a winner for me in this case.

5. Singleton (Object)

Another feature which I like on Kotlin is how easy is to define “singleton”. Consider following example how singleton could be created in java:

Now we can call i.e.

 SingletonInJava.getInstance().doSomething()

Kotlin has a feature to define a singleton in a very tricky way. You can use a keyword object which allows to you define an object which exists only as a single instance.

6. Functional Programming

A combination of lambda expression and the Kotlin library makes our life easier when working with collections:

or more

7. Type Inference

In Kotlin, you do not have to specify the type of each variable explicitly:

8. Default Arguments

In Java, we often have to duplicate code in order define different variants of a method or constructor:

All this stuff we can remove when we switch to Kotlin by using default arguments.

9. Named Arguments

Default arguments become more powerful in a combination with named arguments. We will see it for example how can create an instance of our OperatorInfoInKotlin from the previous section:

Now back to Java:

From this Java code, you did not know which values are set without knowledge of the OperatorInfoInJava class.

// Java
new OperatorInfoInJava("Vaclav", false, false, "blabla");

10. Collections

In Kotlin we have higher-order functions, lambda expressions, operator overloading, lazy evaluation and lots of others useful methods to work with the collection.

We will demonstrate on simple tasks:

“What is an average age of employees in the company in Pilsen city?”

(code below is in Java 1.6)

Extension functions and functional programming are very powerful and Kotlin has a lof of useful extension to working with collections.

The Same example we can implement in Kotlin in these steps:

In the first step, we filter and keep all employees which are from the Pilsen city (Czech Republic)

For more info about collection see official documentation or blog post written by Antonio Leiva here.

Where to Start

Thank you for reading…

--

--

Vaclav Souhrada

Android Developer | Kotlin enthusiast | Czech Kotlin User Group organizer (www.kotliners.cz)