Basic examples

suggest change

The Unit return type declaration is optional for functions. The following functions are equivalent.

fun printHello(name: String?): Unit {
    if (name != null)
        println("Hello ${name}")
}

fun printHello(name: String?) {
    ...
}

Single-expression functions: when a function returns a single expression, the curly braces can be omitted and the body is specified after the = symbol.

fun double(x: Int): Int = x * 2

Explicitly declaring the return type is optional when it can be inferred by the compiler:

fun double(x: Int) = x * 2

String interpolation: Using string values is easy.

int num = 10;
String s = "i = " + num;
val num = 10
val s = "i = $num"

In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). For example, a regular variable of type String cannot hold null:

var a: String = "abc"
a = null // compilation error

To allow nulls, declare a variable as a nullable string, written String?:

var b: String? = "abc"
b = null // ok

In Kotlin, == checks for equality of values. By convention, an expression like a == b is translated to:

a?.equals(b) ?: (b === null)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents