Why Kotlin?

Which is in Java but better in Kotlin

Kotlin has tons of builtin methods while you are using an array you don’t have to use stream library like in java.

val array = arrayOf(1, 2, 3, 4, 5)
val sum = array.sum()
val first = array.first()
val last = array.last()
val biggest = array.maxOrNull()

You don’t have to create getter and setter methods for fields

var name = "John"
    get() = field.toUpperCase()
    set(value) {
        field = value.toLowerCase()
    }

You can use any Java library or api written in Java in Kotlin

import java.util.*
fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    print("Enter your name: ")
    val name = scanner.nextLine()
    println("Name is: $name")
    scanner.close()
}

What does Java doesn’t have but Kotlin does have?

Kotlin has string templates

val name = "John"
println("Hello, $name")

Kotlin has null safety, safe calls, elvis operator

val name: String? = null
val length = name?.length ?: -1
println(length ?: "No name")

Kotlin has data classes

data class Person(val name: String, val age: Int)
val John = Person("John", 30)
val anotherJohn = Person("John", 30)
println(John.equals(anotherJohn))

Kotlin has keyword arguments like in Python

fun sayHi(name: String = "No one", age: Integer) = println("Hi, $name, you are $age years old")
sayHi(age = 30)

Kotlin has ranges like in Python

println(5 in 1..10)
for(i in 1..10) {
    println(i)
}

Kotlin has operator overloading

data class Point(val x: Int, val y: Int)

operator fun Point.unaryMinus() = Point(-x, -y)

val point = Point(10, 20)

fun main() {
   println(-point)  // prints "Point(x=-10, y=-20)"
}

Kotlin has infix functions

infix fun Int.powerOf(n: Int): Int {
    return this.pow(n)
}
println(2 powerOf 3)

Kotlin has extension functions

fun MutableList<Int>.swap(index1: Int, index2: Int) {
    val tmp = this[index1] // 'this' corresponds to the list
    this[index1] = this[index2]
    this[index2] = tmp
}
val list = mutableListOf(1, 2, 3)
list.swap(0, 2) // 'this' inside 'swap()' will hold the value of 'list'

Kotlin has objects that don’t have any nontrivial supertypes

val person = object {
    val name = "John"
    val age = 30
}
println(person.name)

Kotlin has destructuring declarations

data class Person(val name: String, val age: Int)
val (name, age) = Person("John", 30)

Kotlin has scope functions

data class Person(var name: String, var age: Int = 0, var city: String = "")
val adam = Person("Adam").apply {
    age = 32
    city = "London"        
}
println(adam) // Person(name=Adam, age=32, city=London)

Kotlin has smart casts

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        return obj.length
    }
    return null
}

Kotlin

GitHub

View Github