kotlin-basic-syntax.md

#Basic syntax overview

This is a collection of basic syntax elements with examples. At the end of every section, you'll find a link to a detailed description of the related topic.

You can also learn all the Kotlin essentials with the free Kotlin Core track by JetBrains Academy.


#Package definition and imports

Package specification should be at the top of the source file:

kotlinpackage my.demo

import kotlin.text.*

// ...

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:

kotlinfun main() {
    println("Hello world!")
}

Another form of main accepts a variable number of String arguments:

kotlinfun main(args: Array<String>) {
    println(args.contentToString())
}

print prints its argument to the standard output:

kotlinprint("Hello ")
print("world!")

println prints its arguments and adds a line break, so that the next thing you print appears on the next line:

kotlinprintln("Hello world!")
println(42)

#Read from the standard input

The readln() function reads from the standard input. This function reads the entire line the user enters as a string.

You can use the println(), readln(), and print() functions together to print messages requesting and showing user input:

kotlin// Prints a message to request input
println("Enter any word: ")

// Reads and stores the user input. For example: Happiness
val yourWord = readln()

// Prints a message with the input
print("You entered the word: ")
print(yourWord)
// You entered the word: Happiness

For more information, see Read standard input.


#Functions

A function with two Int parameters and Int return type:

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

A function body can be an expression. Its return type is inferred:

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

A function that returns no meaningful value:

kotlinfun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

Unit return type can be omitted:

kotlinfun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

See Functions.


#Variables

In Kotlin, you declare a variable starting with a keyword, val or var, followed by the name of the variable.

Use the val keyword to declare variables that are assigned a value only once. These are immutable, read-only local variables that can't be reassigned a different value after initialization:

kotlin// Declares the variable x and initializes it with the value of 5
val x: Int = 5
// 5

Use the var keyword to declare variables that can be reassigned. These are mutable variables, and you can change their values after initialization:

kotlin// Declares the variable x and initializes it with the value of 5
var x: Int = 5
// Reassigns a new value of 6 to the variable x
x += 1
// 6

Kotlin supports type inference. When declaring a variable, you can omit the type after the variable name:

kotlin// Declares the variable x with the value of 5; `Int` type is inferred
val x = 5
// 5

Variables must be initialized before use:

kotlin// Initializes the variable x at the moment of declaration
val x = 5

// Declares the variable c without initialization; type is required
val c: Int
// Initializes the variable c after declaration
c = 3

Top-level variables:

kotlinval PI = 3.14
var x = 0

fun incrementX() {
    x += 1
}

For information about declaring properties, see Properties.


#Creating classes and instances

To define a class, use the class keyword:

kotlinclass Shape

Properties of a class can be listed in its declaration or body:

kotlinclass Rectangle(val height: Double, val length: Double) {
    val perimeter = (height + length) * 2
}

fun main() {
    val rectangle = Rectangle(5.0, 2.0)
    println("The perimeter is ${rectangle.perimeter}")
}

Inheritance between classes is declared by a colon (:). Classes are final by default; to make a class inheritable, mark it as open:

kotlinopen class Shape

class Rectangle(val height: Double, val length: Double): Shape() {
    val perimeter = (height + length) * 2
}

See Classes and Objects and instances.


#Comments

Kotlin supports single-line and multi-line comments:

kotlin// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */

/* Block comments
/* can be nested */ */

See Documenting Kotlin Code.


#String templates

kotlinvar a = 1
val s1 = "a is $a"

a = 2
val s2 = "${s1.replace("is", "was")}, but now is $a"

See String templates.


#Conditional expressions

kotlinfun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

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

kotlinfun maxOf(a: Int, b: Int) = if (a > b) a else b

See [if-expressions]().


#for loop

kotlinval items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}

// Or using indices:
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}

See [for loop]().


#while loop

kotlinval items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}

See [while loop]().


#when expression

kotlinfun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }

See [when expressions]().


#Ranges

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

kotlinval x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}

Iterate over a range or progression:

kotlinfor (x in 1..5) {
    print(x)
}

for (x in 1..10 step 2) {
    print(x)
}

for (x in 9 downTo 0 step 3) {
    print(x)
}

See [Ranges and progressions]().


#Collections

Iterate over a collection:

kotlinfor (item in items) {
    println(item)
}

Check if a collection contains an object:

kotlinwhen {
    "orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
}

Using lambda expressions:

kotlinval fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
    .filter { it.startsWith("a") }
    .sortedBy { it }
    .map { it.uppercase() }
    .forEach { println(it) }

See [Collections overview]().


#Nullable values and null checks

Nullable type names have ? at the end (e.g., Int?).

kotlinfun parseInt(str: String): Int? {
    return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    if (x != null && y != null) {
        // x and y are automatically cast to non-nullable
        println(x * y)
    } else {
        println("'$arg1' or '$arg2' is not a number")
    }
}

See [Null-safety]().


#Type checks and automatic casts

The is operator checks if an expression is an instance of a type.

kotlinfun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String`
        return obj.length
    }
    return null
}

See [Type casts]().