Kotlin: Why you should totally switch to Kotlin

It’s time to start using a modern programming language

KOTLIN is developed by JetBrains, and the fact that these are the people behind a suite of IDEs, such as IntelliJ and ReSharper, really shines through in Kotlin. It’s pragmatic and concise, and makes coding a satisfying and efficient experience.

Although Kotlin compiles to both JavaScript and soon machine code, I’ll focus on its prime environment, the JVM.
So here’s a couple of reasons why you should totally switch to Kotlin (in no particular order):

1. Java Interoperability

Kotlin is 100% interoperable with Java. You can literally continue work on your old Java projects using Kotlin. All your favorite Java frameworks are still available, and whatever framework you’ll write in Kotlin is easily adopted by your stubborn Java loving friend.

2. Familiar Syntax

Kotlin isn’t some weird language born in academia. Its syntax is familiar to any programmer coming from the OOP domain, and can be more or less understood from the get go. There are of course some differences from Java such as the reworked constructors or the val var variable declarations. The snippet below presents most of the basics:
 
class Foo {

    val b: String = "b"     // val means unmodifiable
    var i: Int = 0          // var means modifiable

    fun hello() {
        val 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

}

3. String Interpolation

It’s as if a smarter and more readable version of Java’s String.format() was built into the language:
 
val x = 4
val y = 7
print("sum of $x and $y is ${x + y}")  // sum of 4 and 7 is 11
   

4. Type Inference

Kotlin will infer your types wherever you feel it will improve readability:

val a = "abc" // type inferred to String
val b = 4 // type inferred to Int

val c: Double = 0.7 // type declared explicitly
val d: List = ArrayList() // type declared explicitly


5. The When Expression

The switch case is replaced with the much more readable and flexible when expression:
 
when (x) {
    1 -> print("x is 1")
    2 -> print("x is 2")
    3, 4 -> print("x is 3 or 4")
    in 5..10 -> print("x is 5, 6, 7, 8, 9, or 10")
    else -> print("x is out of range")
}

It works both as an expression or a statement, and with or without an argument:
 
val res: Boolean = when {
    obj == null -> false
    obj is String -> true
    else -> throw IllegalStateException()
} 

6. Null Safety

Java is what we should call an almost statically typed language. In it, a variable of type String is not guaranteed to refer to a String— it might refer to null. Even though we are used to this, it negates the safety of static type checking, and as a result Java developers have to live in constant fear of 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 // compile error


var b: String? = "xyz"
b = null // no problem


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 cumbersome, it’s really a breeze thanks to a few of its features. We still have smart casts, which casts nullable types to non-null wherever possible:

if (b == null) return
val x = b.length // no problem


We could also use a safe call ?., which evaluates to null instead of throwing a NPE:

val x = b?.length // type of x is nullable Int

Safe calls can be chained together to avoid those nested if-not-null checks we sometimes write in other languages, and if we want a default value other than null we can use the elvis operator ?::

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

If none of that works for you, and you absolutely need a NPE, you will have to ask for it explicitly:

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

Comments

Popular posts from this blog

The Top 5 Phones for Installing Custom ROM

The Top 5 HTML Frameworks

What is the Internet of Things?