Basic Syntax
Package definition and imports
Package specification should be at the top of the source file:
1. package my.demo
3. import kotlin.text.*
5. // ...
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
7. fun main() {
8. print("sum of 3 and 5 is ")
9. println(sum(3, 5))
10. }
Function with an expression body and inferred return type:
1. //sampleStart
2. fun sum(a: Int, b: Int) = a + b
3. //sampleEnd
5. fun main() {
6. println("sum of 19 and 23 is ${sum(19, 23)}")
7. }
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
7. fun main() {
8. printSum(-1, 8)
9. }
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
7. fun main() {
8. printSum(-1, 8)
9. }
See Functions.
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
5. fun incrementX() {
6. x += 1
7. }
8. //sampleEnd
10. fun main() {
11. println("x = $x; PI = $PI")
12. incrementX()
13. println("incrementX()")
14. println("x = $x; PI = $PI")
15. }
See also Properties And Fields.
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
3. /* This is a block comment
4. on multiple lines. */
Block comments in Kotlin can be nested.
1. /* The comment starts here
2. /* contains a nested comment */
3. and ends here. */
See Documenting Kotlin Code for information on the documentation comment syntax.
String templates
1. fun main() {
2. //sampleStart
3. var a = 1
4. // simple name in template:
5. val s1 = "a is $a"
7. a = 2
8. // arbitrary expression in template:
9. val s2 = "${s1.replace("is", "was")}, but now is $a"
10. //sampleEnd
11. println(s2)
12. }
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
11. fun main() {
12. println("max of 0 and 42 is ${maxOf(0, 42)}")
13. }
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
5. fun main() {
6. println("max of 0 and 42 is ${maxOf(0, 42)}")
7. }
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. // ...
3. }
Use a function returning nullable value:
1. fun parseInt(str: String): Int? {
2. return str.toIntOrNull()
3. }
5. //sampleStart
6. fun printProduct(arg1: String, arg2: String) {
7. val x = parseInt(arg1)
8. val y = parseInt(arg2)
10. // Using `x * y` yields error because they may hold nulls.
11. if (x != null && y != null) {
12. // x and y are automatically cast to non-nullable after null check
13. println(x * y)
14. }
15. else {
16. println("'$arg1' or '$arg2' is not a number")
17. }
18. }
19. //sampleEnd
22. fun main() {
23. printProduct("6", "7")
24. printProduct("a", "7")
25. printProduct("a", "b")
26. }
or
1. fun parseInt(str: String): Int? {
2. return str.toIntOrNull()
3. }
5. fun printProduct(arg1: String, arg2: String) {
6. val x = parseInt(arg1)
7. val y = parseInt(arg2)
9. //sampleStart
10. // ...
11. if (x == null) {
12. println("Wrong number format in arg1: '$arg1'")
13. return
14. }
15. if (y == null) {
16. println("Wrong number format in arg2: '$arg2'")
17. return
18. }
20. // x and y are automatically cast to non-nullable after null check
21. println(x * y)
22. //sampleEnd
23. }
25. fun main() {
26. printProduct("6", "7")
27. printProduct("a", "7")
28. printProduct("99", "b")
29. }
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. }
8. // `obj` is still of type `Any` outside of the type-checked branch
9. return null
10. }
11. //sampleEnd
14. fun main() {
15. fun printLength(obj: Any) {
16. println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
17. }
18. printLength("Incomprehensibilities")
19. printLength(1000)
20. printLength(listOf(Any()))
21. }
or
1. //sampleStart
2. fun getStringLength(obj: Any): Int? {
3. if (obj !is String) return null
5. // `obj` is automatically cast to `String` in this branch
6. return obj.length
7. }
8. //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 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. }
8. return null
9. }
10. //sampleEnd
13. fun main() {
14. fun printLength(obj: Any) {
15. println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")
16. }
17. printLength("Incomprehensibilities")
18. printLength("")
19. printLength(1000)
20. }
See Classes and Type casts.
for loop
1. fun main() {
2. //sampleStart
3. val items = listOf("apple", "banana", "kiwifruit")
4. for (item in items) {
5. println(item)
6. }
7. //sampleEnd
8. }
or
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. //sampleEnd
8. }
See for loop.
while loop
1. fun main() {
2. //sampleStart
3. val items = listOf("apple", "banana", "kiwifruit")
4. var index = 0
5. while (index < items.size) {
6. println("item at $index is ${items[index]}")
7. index++
8. }
9. //sampleEnd
10. }
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
12. fun main() {
13. println(describe(1))
14. println(describe("Hello"))
15. println(describe(1000L))
16. println(describe(2))
17. println(describe("other"))
18. }
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")
5. if (-1 !in 0..list.lastIndex) {
6. println("-1 is out of range")
7. }
8. if (list.size !in list.indices) {
9. println("list size is out of valid list indices range, too")
10. }
11. //sampleEnd
12. }
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:
1. fun main() {
2. //sampleStart
3. val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
4. fruits
5. .filter { it.startsWith("a") }
6. .sortedBy { it }
7. .map { it.toUpperCase() }
8. .forEach { println(it) }
9. //sampleEnd
10. }
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. }
10. abstract class Shape(val sides: List<Double>) {
11. val perimeter: Double get() = sides.sum()
12. abstract fun calculateArea(): Double
13. }
15. interface RectangleProperties {
16. val isSquare: Boolean
17. }
19. class Rectangle(
20. var height: Double,
21. var length: Double
22. ) : Shape(listOf(height, length, height, length)), RectangleProperties {
23. override val isSquare: Boolean get() = length == height
24. override fun calculateArea(): Double = height * length
25. }
27. class Triangle(
28. var sideA: Double,
29. var sideB: Double,
30. var sideC: Double
31. ) : Shape(listOf(sideA, sideB, sideC)) {
32. override fun calculateArea(): Double {
33. val s = perimeter / 2
34. return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC))
35. }
36. }
See classes and objects and instances.
