Basic Syntax

    It is not required to match directories and packages: source files can be placed arbitrarily in the file system.

    See Packages.

    Program entry point

    An entry point of a Kotlin application is the main function.

    1. fun main() {
    2. println("Hello world!")
    3. }

    Functions

    Function having two Int parameters with Int return type:

    1. //sampleStart
    2. fun sum(a: Int, b: Int): Int {
    3. return a + b
    4. }
    5. //sampleEnd
    6. fun main() {
    7. print("sum of 3 and 5 is ")
    8. println(sum(3, 5))
    9. }

    Function with an expression body and inferred return type:

    1. //sampleStart
    2. fun sum(a: Int, b: Int) = a + b
    3. //sampleEnd
    4. fun main() {
    5. println("sum of 19 and 23 is ${sum(19, 23)}")
    6. }

    Function returning no meaningful value:

    1. //sampleStart
    2. fun printSum(a: Int, b: Int): Unit {
    3. println("sum of $a and $b is ${a + b}")
    4. }
    5. //sampleEnd
    6. fun main() {
    7. printSum(-1, 8)
    8. }

    Unit return type can be omitted:

    1. //sampleStart
    2. fun printSum(a: Int, b: Int) {
    3. println("sum of $a and $b is ${a + b}")
    4. }
    5. //sampleEnd
    6. fun main() {
    7. printSum(-1, 8)
    8. }

    See .

    Variables

    Read-only local variables are defined using the keyword val. They can be assigned a value only once.

    1. fun main() {
    2. //sampleStart
    3. val a: Int = 1 // immediate assignment
    4. val b = 2 // `Int` type is inferred
    5. val c: Int // Type required when no initializer is provided
    6. c = 3 // deferred assignment
    7. //sampleEnd
    8. println("a = $a, b = $b, c = $c")
    9. }

    Variables that can be reassigned use the var keyword:

    1. fun main() {
    2. //sampleStart
    3. var x = 5 // `Int` type is inferred
    4. x += 1
    5. //sampleEnd
    6. println("x = $x")
    7. }

    Top-level variables:

    1. //sampleStart
    2. val PI = 3.14
    3. var x = 0
    4. fun incrementX() {
    5. x += 1
    6. }
    7. //sampleEnd
    8. fun main() {
    9. println("x = $x; PI = $PI")
    10. incrementX()
    11. println("incrementX()")
    12. println("x = $x; PI = $PI")
    13. }

    See also .

    Comments

    Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments.

    1. // This is an end-of-line comment
    2. /* This is a block comment
    3. on multiple lines. */

    See for information on the documentation comment syntax.

    1. fun main() {
    2. //sampleStart
    3. var a = 1
    4. // simple name in template:
    5. val s1 = "a is $a"
    6. a = 2
    7. // arbitrary expression in template:
    8. val s2 = "${s1.replace("is", "was")}, but now is $a"
    9. //sampleEnd
    10. println(s2)
    11. }

    See String templates for details.

    Conditional expressions

    1. //sampleStart
    2. fun maxOf(a: Int, b: Int): Int {
    3. if (a > b) {
    4. return a
    5. } else {
    6. return b
    7. }
    8. }
    9. //sampleEnd
    10. fun main() {
    11. println("max of 0 and 42 is ${maxOf(0, 42)}")
    12. }

    In Kotlin, if can also be used as an expression:

    1. //sampleStart
    2. fun maxOf(a: Int, b: Int) = if (a > b) a else b
    3. //sampleEnd
    4. fun main() {
    5. println("max of 0 and 42 is ${maxOf(0, 42)}")
    6. }

    See if-expressions.

    Nullable values and null checks

    A reference must be explicitly marked as nullable when null value is possible.

    Return null if str does not hold an integer:

    1. fun parseInt(str: String): Int? {
    2. }

    Use a function returning nullable value:

    1. fun parseInt(str: String): Int? {
    2. return str.toIntOrNull()
    3. }
    4. //sampleStart
    5. fun printProduct(arg1: String, arg2: String) {
    6. val x = parseInt(arg1)
    7. val y = parseInt(arg2)
    8. // Using `x * y` yields error because they may hold nulls.
    9. if (x != null && y != null) {
    10. // x and y are automatically cast to non-nullable after null check
    11. println(x * y)
    12. }
    13. else {
    14. println("'$arg1' or '$arg2' is not a number")
    15. }
    16. }
    17. //sampleEnd
    18. fun main() {
    19. printProduct("6", "7")
    20. printProduct("a", "7")
    21. printProduct("a", "b")
    22. }

    or

    1. fun parseInt(str: String): Int? {
    2. return str.toIntOrNull()
    3. }
    4. fun printProduct(arg1: String, arg2: String) {
    5. val x = parseInt(arg1)
    6. val y = parseInt(arg2)
    7. //sampleStart
    8. // ...
    9. if (x == null) {
    10. println("Wrong number format in arg1: '$arg1'")
    11. return
    12. }
    13. if (y == null) {
    14. println("Wrong number format in arg2: '$arg2'")
    15. return
    16. }
    17. // x and y are automatically cast to non-nullable after null check
    18. println(x * y)
    19. //sampleEnd
    20. }
    21. fun main() {
    22. printProduct("6", "7")
    23. printProduct("a", "7")
    24. printProduct("99", "b")
    25. }

    See Null-safety.

    Type checks and automatic casts

    The is operator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a specific type, there’s no need to cast it explicitly:

    1. //sampleStart
    2. fun getStringLength(obj: Any): Int? {
    3. if (obj is String) {
    4. // `obj` is automatically cast to `String` in this branch
    5. return obj.length
    6. }
    7. // `obj` is still of type `Any` outside of the type-checked branch
    8. return null
    9. }
    10. //sampleEnd
    11. fun main() {
    12. fun printLength(obj: Any) {
    13. println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
    14. }
    15. printLength("Incomprehensibilities")
    16. printLength(1000)
    17. printLength(listOf(Any()))
    18. }

    or

    1. //sampleStart
    2. fun getStringLength(obj: Any): Int? {
    3. if (obj !is String) return null
    4. // `obj` is automatically cast to `String` in this branch
    5. return obj.length
    6. }
    7. //sampleEnd
    8. fun main() {
    9. fun printLength(obj: Any) {
    10. println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
    11. }
    12. printLength("Incomprehensibilities")
    13. printLength(1000)
    14. printLength(listOf(Any()))
    15. }

    or even

    1. //sampleStart
    2. fun getStringLength(obj: Any): Int? {
    3. // `obj` is automatically cast to `String` on the right-hand side of `&&`
    4. if (obj is String && obj.length > 0) {
    5. return obj.length
    6. }
    7. return null
    8. }
    9. //sampleEnd
    10. fun main() {
    11. fun printLength(obj: Any) {
    12. println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")
    13. }
    14. printLength("Incomprehensibilities")
    15. printLength("")
    16. printLength(1000)
    17. }

    See Classes and .

    for loop

    1. fun main() {
    2. //sampleStart
    3. val items = listOf("apple", "banana", "kiwifruit")
    4. for (index in items.indices) {
    5. println("item at $index is ${items[index]}")
    6. }
    7. }

    See .

    1. //sampleStart
    2. val items = listOf("apple", "banana", "kiwifruit")
    3. var index = 0
    4. while (index < items.size) {
    5. println("item at $index is ${items[index]}")
    6. index++
    7. }
    8. //sampleEnd
    9. }

    See while loop.

    when expression

    1. //sampleStart
    2. fun describe(obj: Any): String =
    3. when (obj) {
    4. 1 -> "One"
    5. "Hello" -> "Greeting"
    6. is Long -> "Long"
    7. !is String -> "Not a string"
    8. else -> "Unknown"
    9. }
    10. //sampleEnd
    11. fun main() {
    12. println(describe(1))
    13. println(describe("Hello"))
    14. println(describe(1000L))
    15. println(describe(2))
    16. println(describe("other"))
    17. }

    See when expression.

    Ranges

    Check if a number is within a range using in operator:

    1. fun main() {
    2. //sampleStart
    3. val x = 10
    4. val y = 9
    5. if (x in 1..y+1) {
    6. println("fits in range")
    7. }
    8. //sampleEnd
    9. }

    Check if a number is out of range:

    1. fun main() {
    2. //sampleStart
    3. val list = listOf("a", "b", "c")
    4. if (-1 !in 0..list.lastIndex) {
    5. println("-1 is out of range")
    6. }
    7. if (list.size !in list.indices) {
    8. println("list size is out of valid list indices range, too")
    9. }
    10. //sampleEnd
    11. }

    Iterating over a range:

    1. fun main() {
    2. //sampleStart
    3. for (x in 1..5) {
    4. print(x)
    5. }
    6. //sampleEnd
    7. }

    or over a progression:

    1. fun main() {
    2. //sampleStart
    3. for (x in 1..10 step 2) {
    4. print(x)
    5. }
    6. println()
    7. for (x in 9 downTo 0 step 3) {
    8. print(x)
    9. }
    10. //sampleEnd
    11. }

    See Ranges.

    Collections

    Iterating over a collection:

    1. fun main() {
    2. val items = listOf("apple", "banana", "kiwifruit")
    3. //sampleStart
    4. for (item in items) {
    5. println(item)
    6. }
    7. //sampleEnd
    8. }

    Checking if a collection contains an object using in operator:

    1. fun main() {
    2. val items = setOf("apple", "banana", "kiwifruit")
    3. //sampleStart
    4. when {
    5. "orange" in items -> println("juicy")
    6. "apple" in items -> println("apple is fine too")
    7. }
    8. //sampleEnd
    9. }

    Using lambda expressions to filter and map collections:

    See Collections overview.

    Creating basic classes and their instances

    1. fun main() {
    2. //sampleStart
    3. val rectangle = Rectangle(5.0, 2.0)
    4. val triangle = Triangle(3.0, 4.0, 5.0)
    5. //sampleEnd
    6. println("Area of rectangle is ${rectangle.calculateArea()}, its perimeter is ${rectangle.perimeter}")
    7. println("Area of triangle is ${triangle.calculateArea()}, its perimeter is ${triangle.perimeter}")
    8. }
    9. abstract class Shape(val sides: List<Double>) {
    10. val perimeter: Double get() = sides.sum()
    11. abstract fun calculateArea(): Double
    12. }
    13. interface RectangleProperties {
    14. val isSquare: Boolean
    15. }
    16. class Rectangle(
    17. var height: Double,
    18. var length: Double
    19. ) : Shape(listOf(height, length, height, length)), RectangleProperties {
    20. override val isSquare: Boolean get() = length == height
    21. override fun calculateArea(): Double = height * length
    22. }
    23. class Triangle(
    24. var sideA: Double,
    25. var sideB: Double,
    26. var sideC: Double
    27. ) : Shape(listOf(sideA, sideB, sideC)) {
    28. override fun calculateArea(): Double {
    29. val s = perimeter / 2
    30. return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC))
    31. }
    32. }

    See classes and .