What Kotlin Is All About

And why you should bet on it.

Okanagan Lake by Darren Hull

What Is Kotlin?

There is a new programming language out in the world! It goes by the name of Kotlin.

Kotlin is a statically typed language brought to you by JetBrains. It runs on Java Virtual Machine, so if you are someone who prefers to code in Java, you will find the migration to Kotlin to be so easy that soon you won’t be able to think of a situation where Java would be a better choice than Kotlin.

Developers who have used other products of JetBrains like IntelliJ and ReSharper will probably agree with me when I say that Kotlin is another one of JetBrains’ great products. Users of Kotlin have claimed it to be pragmatic and concise and makes coding a satisfying and efficient experience.

With Kotlin, you can build applications for:

Kotlin was first introduced in 2011 and was open sourced in 2012 under the Apache license. It has managed to gain so much popularity in the recent years that Google declared it as an official language for Android Development at Google I/O 2017.


Why Kotlin?

So why should you try Kotlin? Why not stick with Java for Android app development?

Here are the Top 5 reasons why a developer should consider Kotlin:

Interoperable with Java

Kotlin is completely interoperable with Java. Say you are currently in the middle of a Java project. To move to Kotlin, you don’t need to change anything in your project, except the file extension, which now needs to be .kt. All the Java frameworks that you have come to rely on will still be there.

You have seen this Syntax somewhere

Kotlin’s syntax will be familiar to any developer who has had dealings in the Object-Oriented Programming domain. Of course, there will be some differences like reworked constructors and the val and var variable declarations. Check out the code below and see if you can make any sense of it:

class Foo {
    val b: String = "b"
val i: Int = 0
    fun hello() {
var str = "Hello"
print("$str World")
}
    fun sum(x: Int, y: Int): Int {
return x + y
}
    fun maxOf(a: Float, b: Float) = if (a > b) a else b
}

Smart Casts

Kotlin’s compiler can track your logic and auto-cast types wherever possible. What this means is that there will be no more instanceof checks followed by explicit casts:

if (obj is String) {
print(obj.toUpperCase())
}

Better Lambdas

Although this feature has been introduced in Java’s 8th version, Android developers need to use other toolchains to use the feature in development. Kotlin provides lambda expression from the first version itself.

Kotlin has one of the best lambda systems in the market. It is perfectly balanced between readability and terseness, all thanks to some really clever design choices by JetBrains. The syntax is first of all very straightforward:

val sum = { x: Int, y: Int -> x + y } // type: (Int, Int) -> Int
val res = sum(4,7) // res == 11

Now the reasons why I said Kotlin’s lambda system to be one of the best are:

  1. Method parentheses can be moved or omitted if the lambda is the last or the only argument of a method.
  2. If we choose not to declare the argument of a single-argument-lambda it’ll be implicitly declared under the name it.

These facts, when brought together can make the following three lines equivalent to each other:

numbers.filter({ x-> x.isPrime() })
numbers.filter { x-> x.isPrime() }
numbers.filter { it.isPrime() }

This allows us to write concise, beautiful and functional code 😍

persons
.filter { it.age >= 18 }
.sortedBy { it.name }
.map { it.email }
.forEach { print(it) }

Kotlin’s lambda system when combined with extension functions make it ideal for DSL creation. Check out Anko for an example of a DSL that aims to enhance Android developement:

verticalLayout {
padding = dip(30)
editText {
hint = “Name”
textSize = 24f
}
editText {
hint = “Password”
textSize = 24f
}
button(“Login”) {
textSize = 26f
}
}

Data Class

These classes exist only to group data. A typical data class in Java has tons of boilerplate code. For example, an Employee data class in Java will look like this.

public class Employee {
private String name;
private long salary;

public Employee(String name, long salary) {
this.name = name;
this.salary = salary;
}
    public String getName() {
return name;
}
    public void setName(String name) {
this.name = name;
}
    public long getSalary() {
return salary;
}

public void setSalary(long salary) {
this.salary = salary;
}
}

As one can see, a Java developer has to go through all the pain of writing such a huge code to achieve something that in Kotlin can be done in just one line like this:

data class Employee(var name: String?, var salary: Long)

Null Safety

Kotlin aims at eliminating the perils of null references from the code, which is often called as The Billion Dollar Mistake. In Java, accessing a member of null reference results in null pointer exception.

Java is usually considered as the almost statically typed language. A variable of type string does not necessarily always return a String. The variable could also refer to a null.

A Java developer might be used to this, but Java can negate the safety of static type checking, and as a result, Java developers have to life under the fear of Null Pointer Exceptions (NPEs).

Kotlin resolves this by distinguishing between non-null types and nullable types. Types are non-null by default, and can be made nullable by adding a ? like so:

var a: String = "abc"
a = null
var b: String? = "xyz"
b = null

Kotlin forces you to guard against NPEs whenever you access a nullable type:

val x = b.length // compile error: b might be null

And while this might seem painstaking, it’s really a breeze thanks to a few of Kotlin’s features. We still have smart casts, which casts nullable types to non-null wherever possible:

if (b == null) return
val x = b.length

?. can help you evaluate to null instead of throwing a NPE:

val x = b?.length 

Safe calls can be chained together to avoid those nested if-not-null checks that some developers write. If you want a default value other than null, you can use the elvis operator ?:

val name = ship?.captain?.name ?: "unknown"

If all else fails, you can explicitly ask for an NPE:

val x = b?.length ?: throw NullPointerException()
val x = b!!.length // same as above

Other Forms of Kotlin

KotlinJS

Kotlin code can be transpiled to JavaScript source code. It provides a series of statically typed interfaces to interact with the DOM, allowing us to create and update DOM elements.

KotlinJS is very similar to vanilla JS and can be easily understood by JavaScript developers:

There are multiple ways to transpile Kotlin to JavaScript.

Make sure that you have a .html file that has the following code:

The recommended approach is to use Gradle. You can also build JavaScript projects directly from IntelliJ IDEA, use Maven or compile the code manually from the command line.

When compiling to JavaScript, Kotlin will output two main files:

  • kotlin.js — This is the runtime and standard library. This doesn’t change between applications and is tied to the version of Kotlin being used.
  • {module}.js — The actual code from the application. All files comply into a single JavaScript file which has the same name as the module.

Each of these files will also have a corresponding {file}.meta.js meta file which will be used for reflection and other functionality.

Given the following code snippet:

fun main(args: Array<String>) {
println("Hello JavaScript!")
}

Kotlin compiler would generate the following output

ConsoleOutput
|_ lib
|_ kotlin.js
|_ kotlin.meta.js
|_ ConsoleOutput.js
|_ ConsoleOutput.meta.js

Kotlin/Native

Kotlin/Native is a technology for compiling Kotlin to native binaries that run without any VM. It comprises an LLVM-based backend for Kotlin compiler and a native implementation of the Kotlin runtime library.

Kotlin/Native is primarily designed to allow compilation for platforms where virtual machines are not desirable or possible (iOS or embedded devices), or where the developer needs to produces a self-container program that does not need the additional runtime.

Kotlin/Native currently supports the following platforms:

  • Windows (x86_64)
  • Linux (x86_64, arm32, MIPS, MIPS little endian)
  • MacOS (x86_64)
  • iOS (arm64)
  • Android (arm32 and arm64)
  • WebAssembly (wasm32)

Sharing Code between Platforms

JetBrains plans to bring Kotlin to all modern application components. The company just announced version 1.2 of the statically typed programming language for modern multiplatform applications.

This major release gives developers the possibility to reuse code between the JVM and JavaScript.

Now you can write the business logic of your application once, and reuse it across all tiers of your application — the backend, the browser, frontend, and the Android mobile app. We’re also working on libraries to help you reuse more of the code, such as a cross-platform serialization library — Dmitry Jemerov, principal engineer at JetBrains

Kotlin 1.2 is built to support multiplatform projects. A multiplatform project allows you to build multiple tiers of your application — backend, frontend and Android app — from the same codebase.

Version 1.2 has significantly improved the compilation performance of Kotlin. Kotlin is now about 25% improvement over its previous version (1.1).

Other features of this release include:

  • Improvements to the syntax for passing multiple arguments to an annotation.
  • Support for the lateinit modifier.
  • Smarter smart casts. 😆
  • Improved type inference.
  • New kotlin.math package.
  • New standard library functions.

In The End…

I am Rajat S, a Technical Content Writer at GeekyAnts. Aspiring Coder who has a long way to go. A Die-Hard DC Comics Fan who loves Marvel Movies. 😛 Follow me on Twitter and Facebook to know about all the amazing things that are happening at GeekyAnts.

Thanks to ayush bansal, a software engineer at GeekyAnts, for helping me make sense out of Kotlin.

And Thank You for reading! Please do 👏 if you liked this post 😄