Kotlin Functions


Basic Usage


fun keyword is used to define the function
a and b are input parameters of type Int
Int (after brackets) is matching the return type

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

Same expression can be shortened (omit function brackets), meaning that return type is infered.
Return keyword can be also omited in such expression body

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

Return type can also be omitted (you don’t have to use void return type) if function does not return anything

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


Simple method call:

val result = sum(2, 3)

Named arguments in method call:

val result = sum(a = 1, b = 5)

Support of default arguments (if parameter is not provided in method call):

fun write(content: String, destination: String = "/tmp/") { ... }


This article needs improvement. You can help improve this article. You can also write similar articles and help the community.