Java has become legacy. It can’t evolve in to a modern language while keeping its backward compatibility. But it has given us a wonderful JVM ecosystem and lead to creation of many good languages Groovy, Scala, Clojure, Kotlin.

Welcome the newest baby Kotlin
Kotlin was born in 2011, But it gained popularity last year after google announced it as official language for Android. Kotlin has brought powerful features from many other JVM languages. Let take a quick glance at benefits of Kotlin for a Java developer.

Never worry about NPEs
Every Java programmer hates Null Pointer Exceptions thrown at Runtime. Kotlin provides first class support to avoid null references at compile time. All objects are non-nullable by default and you have to use ? operator to define nullable types. Compiler will force you to use safe call operator ?. to access nullable objects. You can also use elvis operator ?: to assign default values.

var name = "Kotlin"
var nameLength = name.length // Works
name = null // Compilation Error : Null can not be a value of a non-null type String

var nullableName : String? = null

// Compilation Error : Only safe (?.) or non-null asserted (!!.)
// calls are allowed on a nullable receiver of type String?
var nameLength = nullableName.length 

nameLength = nullableName?.length ?: 0
view rawnullSafety.kt hosted with ? by GitHub
No need to provide explicit type declaration.
Kotlin automatically infers types, so you don’t need to declare it explicitly. You can simply define variables using val for final variables and var for non-final variables. Note type can be inferred only if both declaration and assignment is done in single statement.

var number = 10
number = "Kotlin" // Compilator Error: Type Mismatch. Required Int, Found String.

val name = "Kotlin"
name = "Hello" // Compilation Error: val can't be reassigned.

var i = 0;
i = 10 //Works
view rawtypeInference.kt hosted with ? by GitHub
Avoid convoluted String formatting.
In Kotlin you can use String templates for easier formatting of Strings. $is used to reference a variable and you can use ${} for complex expressions

var name = "Kotlin"

println("Hello $name")
println("Length is ${name.length} !")
view rawStringtemplates.kt hosted with ? by GitHub
No boiler plate code required to create simple POJOs.
Kotlin provides data classes for objects used to simply hold values. It automatically generates equals , hashCode , toString , copy , getters and setters ( for properties defined as var) methods for data classes. You can also do object deconstruction of data class to extract properties to variables.

data class Person(val name:String, val age:Int)

val person = Person("John", 20)
println(person) // Prints Person(name=John, age=20)

val (name, age) = person //Object deconstruction

println("Age of $name is $age") //Age of John is 20
view rawdataClasses.kt hosted with ? by GitHub
You can avoid Builder classes and redundant method overloads.
Kotlin supports named method parameters so you don’t need to create builders in most cases. Also, Kotlin supports default method parameters so you don’t need to create redundant overloaded methods to pass default values.

data class Person(val firstName: String, val email: String, val age: Int = 0)

val person = Person(firstName = "John", email = "", age = 0)//Default age is 0
println(person) //Person(firstName=John,, age=0)

fun formatDate(date: LocalDate,format : String = "MM/dd/YY") : String{
    return DateTimeFormatter.ofPattern(format).format(date)
//You don't need overloaded version of formatDate to support default format.
println(formatDate( // Prints 04/06/18
println(formatDate(, "dd/MM/YY")) // Prints 06/04/18
view rawdefaultAndNamedParameters.kt hosted with ? by GitHub
You no longer need guava library to statically initialize collections.
Kotlin provides concise way to initialize collections inline using listOf , mapOf , setOf methods. Maps also support intuitive syntax key to value for initialization. It also provides deconstruction of Map key, values for easy iteration.

Top 5 Books for Learn Core Java for Beginners

val numbers = listOf(1,2,3,4,5)
val colors = setOf("Blue", "Green", "Red")

val numberWords = mapOf( 1 to "One", 2 to "Two" , 3 to "Three")

for ( ( number , word) in numberWords){
    println("$number = $word")
view rawinlineCollections.kt hosted with ? by GitHub
You don’t need a complicated way to create Singletons.
Kotlin supports object declaration to create Singletons in single line.

//Becomes singleton when you declare as object
object Config {
  val configProperties = loadConfig()

  fun loadConfig():Map<String, String>{
      //Ideally initialize from external file
      return mapOf("" to "kotlin-example")
view rawsigletonClass.kt hosted with ? by GitHub
You don’t need unnecessary local variables
In Kotlin, constructs like try and when are expressions that returns value. For e.g You can assign result of try to a variable instead of creating a local variable. Similarly for when can be used as expression. when is equivalent to switch in Java, but it is much more powerful.

fun readNumber(str: String){

    //Try is an expression, you can directly assign value to variable
    val number = try {
    }catch (e: NumberFormatException){

//When (Equivalent of switch in Java) is also an expression.
fun evenOrOdd(i : Int) = when{
    i % 2 == 0 -> "Even"
    else -> "Odd"

println(evenOrOdd(10))//prints "Even"
view rawexpressions.kt hosted with ? by GitHub
You will avoid Class Cast exceptions.
Kotlin provides is operator (equivalent to instanceOf in Java) to check if object is specific type . Using is operator will automatically do casting for you. This will prevent Class Cast exception when you cast to wrong type.

interface Result {}
//Classes Success and Failure both implement Result interface
//and have different fields.
class Success(val message: String) : Result
class Failure(val error: Throwable) : Result

fun smartCastExample() {

  val results = listOf(Success("completed"), Failure(RuntimeException("some thing went wrong")))

  results.forEach { result ->
      when {
         result is Success -> println(result.message)  //Automatically converts result to type Success
         result is Failure -> println(result.error)  //Automatically converts result to type Failure
      //Prints completed
      //java.lang.RuntimeException: some thing went wrong
view rawsmartCast.kt hosted with ? by GitHub
You don’t need to repeat the variable name to call sequence methods in same object.
Kotlin provides with construct to easily call sequence of methods on same object without having to repeat the variable name. We generally use builder pattern and method chaining to that in Java. Kotlin makes it easy to do similar thing even for non-builder classes.

Kotlin also provides apply extension function to achieve the same thing.

val date = with(GregorianCalendar()){
    //You don't have to repeat cal. for every method call.
    set(Calendar.YEAR, 2018)
    set(Calendar.DATE, 10)
    set(Calendar.MONTH, 1)

val date = GregorianCalendar().apply{
    //You don't have to repeat cal. for every method call.
    set(Calendar.YEAR, 2018)
    set(Calendar.DATE, 10)
    set(Calendar.MONTH, 1)
view rawobjectAccessSimplification.kt hosted with ? by GitHub
You don’t need boilerplate code to use delegation or decorator pattern.
To favor composition over inheritance, we often use delegation or decorator pattern, but we had to duplicate every method of delegated class in wrapper class. Kotlin provides first class support to simplify delegation using by operator. It will automatically implement necessary methods to call methods of delegated class. Of course, you can override specific methods when need to.

class Headers<T>(val delegate : Map<String, T>) : Map<String, T> by delegate

//Headers has all the methods of Map interface and delegates it's call to delegate field.
val headers = Headers(mapOf("H1" to "Val1", "H2" to 5))

println(headers.get("H2"))//Prints 5.
view raweasyDelegation.kt hosted with ? by GitHub
You don’t need to a Class to create static functions.
Kotlin supports functions outside of classes, so you don’t need to create a class just for static utility functions.

package hello

fun getHelloString() : String {
    return "Hello, world!"

fun main(args : Array<String>) {

view rawhello.kt hosted with ? by GitHub
You don’t need a hack to modify non-final variables in lambdas.
Java supports lambda by automatically substituting it with anonymous inner classes, but you can’t modify non-final variable inside lambdas. But in Kotlin you can also modify non-final variables within lambda.

An Introduction to Deep Learning

var localVarSum = 0
Stream.of(1,2,3,4).forEach{n ->
    //Non-final local variable can be modified inside lambda
    localVarSum += n
println(localVarSum) // Prints 10
view rawlambdaFinalVars.kt hosted with ? by GitHub
Lazy loading doesn’t require hard work.
Kotlin provides very simple way to lazily initialize a property using lazy keyword.

data class Rectangle(val length: Int, val width : Int){
    val area by lazy {
        //This will be executed lazily only once.
        println("Computing area");
        length * width

val rect = Rectangle(10,20)
println(rect)//Rectangle(length=10, width=20)

println(rect.area) //Prints Computing area followed by 200
println(rect.area) //Doesn't Print Computing area since it's already initialized.
view rawlazyExample.kt hosted with ? by GitHub
You don’t have to totally switch to a new language.
Kotlin interoperates with Java seamlessly, so you can easily integrate with legacy Java code. You can continue to leverage third party Java libraries and frameworks. Unlike Scala, Kotlin doesn’t have it’s own collection library, but extends JDK collections. So you don’t need to write glue code to convert between Java and Kotlin collection types.

val numbers: List<Int> = listOf(100, 20, 30, 4)

//Can pass kotin's Collection<Int> to Java SDK that expects Java List
println(numbers) //Prints [4, 20, 30, 100]
view rawjavaInterOp.kt hosted with ? by GitHub
You can write concise and more readable code.
Kotlin uses method name convention to overload many operators for readability. For e.g method plus is used to overload + operator, minus for - operator, times for * operator, div for / operator and so on. It supports overloading many more operators like %, += , +- , ++,--

data class Point(val x: Int, val y: Int) {
  operator fun plus(other: Point): Point {
      return Point(x + other.x, y + other.y)
  operator fun minus(other: Point): Point {
      return Point(x - other.x, y - other.y)

val p1 = Point(10, 20);
val p2 = Point(30,40)

println(p1 + p2) // Prints Point(x=40, y=60)
println(p1 - p2)
view rawoperatorOverloading.kt hosted with ? by GitHub
Kotlin provides concise way to define ranges using .. operator. It also provides until keyword for excluding boundaries and step operator for skipping items. It has in operator to check for something in range. We can also overload .. operator and in operator by implementing rangeTo and contains methods.

Java VS Kotlin

val numbers = 1..100;//Closed Range
val numbersUpTo10 = 1 until 10 //Exclude boundaries
val evenNumbers = 0 until 10 step 2

val n = 50
//User in operator to check if something in range.
if (n in 1..100){
    println("$n is between 1 and 100")
view rawranges.kt hosted with ? by GitHub
You can easily extend existing JDK classes.
Kotlin support easy way to add extension functions to existing classes. This is a very power feature that helps us to easily expand core language API.

//Define method as className.methodName to add extension function
fun Int.isEven() : Boolean = this % 2 == 0;

println(2.isEven())//Prints true
view rawExtenstionFunctions.kt hosted with ? by GitHub
Why should you use Kotlin?
It boosts your productivity by many fold
It’s statically typed language, so you will catch lot of bugs at compile time.

It has great tooling support. No doubt it’s created by an IDE company

It is created by JetBrains a IDE company which cares for developer productivity.

Avoid many of day to day frustrations of a Java developer.

You get benefits of many best practices (Principles from Effective Java Book) by default.
All classes are final.

Collections are immutable.

Override mandatory keyword instead of optional annotation

No Checked exceptions

No Raw types

Cleaner support for generics.

Non-JVM support.
Kotlin also compiles to Javascript for front end development.

They are also working on adding native runtime to make it run without JVM.

Should you switch to Kotlin?
Kotlin is awesome but it’s not yet perfect. It will take some time to evolve in to a great language. JetBrains and Google are actively behind Kotlin so you can sure be that it will only get better.

If you are an Android developer, you should start using Kotlin immediately.

If you are a Java developer, you might have to consider other factors like team members, company adoption etc. But even if you can’t use it immediately, you should definitely learn this modern piece of beauty.

Finally, As per thoughtworks technology radar, companies can adopt using kotlin in projects when appropriate.

The 10 Websites to Learn Python