View on GitHub

kotlin-cheatsheet

Kotlin cheat sheet

Common Style Guide

Function

val anonymousFunction = fun(x: Int, y: Int): Int { return x + y }
val lambda1 = { x: Int, y: Int -> x + y }
val lambda2: (Int, Int, Int) -> Int = { x, y, z -> x * y * z }

Variable

Flow Control

if expression

when expression

Returns value.

for loop

for (c in "sequence") { ... }
for ((i, c) in "sequence".withIndex()) { println("$i: $c") }

Loop for collection

for (c in 'A'..'Z') { ... }
for (i in intArrayOf(1, 2, 3)) { ... }

Loop for number

Ordinary Order
for (i in 1..10) { ... }
for (i in 1..10 step 3) { ... }

The number just after step must be greater than 0.

Reverse Order
for (i in 10 downTo 5) { ... }
for (i in 10 downTo 5 step 2) { ... }

while loop

while (condition) { ... }
do { ... } while (condition)

Class

Class Common

Data Class

data clss User(name: String, email: Address)

Abstract Class

abstract class AbstractClass {
   abstract val a: Int
   abstract fun b()
}

Enum Class

Sealed Class

Object

Interface

interface Interface {
    val value: Long
    fun interfaceFunction1(): Int
    fun interfaceFunction2() { println(1) }
}
class InheritClass : Interface {
    override val value = 1L
    override fun interfaceFunction1() = 1
}

Type

Basic Type

Collection

List, Map, Array

Alias

Scope Function

Identifier Is extension function The object is represented as return value
also Yes it The Object
let Yes it Result
apply Yes this The Object
run Yes this Result
with No this Result

Delegation

Annotation

use-site

DSL Development

Overload for Java