How to use Kotlin

Kotlin cheat sheet: Tips & tricks

Dmitry Jemerov
Kotlin
© Shutterstock / pinkomelet

Google recently declared Kotlin as a first-class language. This increased visibility means everyone is looking at this programming language. Here, Dmitry Jemerov explains some tips and tricks for dealing with basic syntax, classes, and more in Kotlin.

Kotlin is a new programming language created by JetBrains and targeting the JVM, Android and the browser. Kotlin is concise, safe, and fully interoperable with existing Java and JavaScript code. Kotlin helps avoid common errors such as NPEs and strives to make programming more pleasant.

At the Google I/O conference, Google has announced official support for Kotlin as a language for developing Android applications, meaning that Kotlin development tools are now bundled with Android Studio.

This cheat sheet will introduce you to the most important elements of the Kotlin syntax. To learn more, visit the Kotlin web site here.

Basic Syntax

Hello World

fun main(args: Array<String>) {
    println("Hello, World")
}

Declaring Functions

fun sum(a: Int, b: Int): Int {
    return a + b    
}

Functions with expressive body

fun sum(a: Int, b: Int) = a + b

Declaring variables

val name = "Kotlin"  // can't be changed
var age = 5          // can be changed
age++ 

Variables with nullable types

var middleName: String? = null
middleName.length                    // doesn't compile
val length = middleName?.length ?: 0 // length or 0 if null 

SEE MORE: Kotlin Native serverless tutorial: Fun with Fibonacci

Control Structures

if statement (also replaces ternary operator)

fun max(a: Int, b: Int) = if (a > b) a else b 

for loop

for (element in list) {
    println(element)    
}

for loop with index

for ((index, element) in elements.withIndex()) {
    // String interpolation: $index, $element
    println("Element at $index is $element")   
} 

when (replaces switch). when is an expression, like if

fun whenDemo(x: Number) = when(x) {  
    0 -> "Zero"                      // Equality check
    in 1..4 -> "Four or less"        // Range check
    5, 6, 7 -> "Five to seven"       // Multiple values
    is Byte -> "Byte"                // Type check
    else -> "Some number"
} 

when without expression

fun whenDemo2(x: Number) = when {
    x < 0 -> "Negative"
    x == 0 -> "Zero"
    else -> "Positive"
}

Classes

Primary constructor. val declares a read-only property, var – a mutable one

class Person(val name: String, var age: Int)	
             // name is readonly, age is mutable 

Inheritence

open class Person(val name: String) {
    open fun sayHello() = "Hello from $name"
}

class RussianPerson(name: String) : Person(name) {
    override fun sayHello() = "Privet ot $name"
} 

Properties with acessors

class Person(val name: String, var age: Int) {
    var birthYear: Int
        get() = LocalDate.now().year - age
        set(value) {
            age = LocalDate.now().year - value
        }
} 

Autogenerated equals(), hashCode(), toString(), copy():

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

val olderPerson = person.copy(age = person.age + 1)

SEE MORE: Serverless Kotlin tutorial — You get the best of both worlds

Higher Order Functions

filter() and map()

val adultList = persons
    .filter { it.age >= 18 }
    .map { "${it.name} is ${it.age} years old" } 

use() (replaces Java’s try with resources)

fun printLines(file: File) {
    file.inputStream().bufferedReader().use { reader ->
        for (line in reader.lineSequence()) {
            println(line)
        }
    }
} 

Adding Kotlin to Gradle

Regular project

buildscript {
    // ...
    ext.kotlin_version = '<version to use>'

    dependencies {
        classpath "org.jetbrains.kotlin" +
            "kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin'

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"
} 
Author

Dmitry Jemerov

Dmitry Jemerov is a long-time IntelliJ IDEA developer and one of the earliest contributors to Kotlin. Currently he is leading the Kotlin tooling team. Dmitry is also a co-author of the “Kotlin in Action” book.


Comments
comments powered by Disqus