Kotlin: Basics Cheat Sheet

“Hello, World” program

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

Declaring function

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

Single-expression function

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

Declaring variables

val name = ”Marcin” // Can't be changed
var age = 5 // Can be changed
age++

Variables with nullable types

var name: String? = null
val length: Int
length = name?.length ?: 0
// length, or 0 if name is null
length = name?.length ?: return
// length, or return when name is null
length = name?.length ?: throw Error()
// length, or throw error when name is null

Leave a Reply

Your email address will not be published. Required fields are marked *