CS 346 (W23)
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Functions

Functions are preceded with the fun keyword. Function parameters require types, and are immutable. Return types should be supplied after the function name, but in some cases may also be inferred by the compiler.

Named Functions

Named function have a name assigned to them that can be used to invoke them directly (this is the expected form of a “function” in most cases, and the form that you’re probably expecting).

// no parameters required fun main() { println(sum1(1, 2)) println(sum1(3,4)) } // parameters which require type annotations fun sum1(a: Int, b: Int): Int { return a + b } // return types can be inferred based on the value you return // it's better form to explicitly include the return type in the signature fun sum2(a: Int, b: Int) { a + b // Kotlin knows that (Int + Int) -> Int }

Single-Expression Functions

Simple functions in Kotlin can sometimes be reduced to a single line aka a single-expression function.

// previous example
fun sum(a: Int, b: Int) {
  a + b // Kotlin knows that (Int + Int) -> Int
}

// this is equivilant
fun sum(a: Int, b: Int) = a + b

// this works since we evaluate a single expression
fun minOf(a: Int, b: Int) = if (a < b) a else b

Function Parameters

Default arguments

We can use default arguments for function parameters. When called, a parameter with a default value is optional; if the value is not provided by the caller, the default will be used.

// Second parameter has a default value, so it’s optional fun mult(a:Int, b:Int = 1): Int { return a * b } fun main() { mult(1) // 1 mult(5,2) // 10 // mult() will throw an error, `a` must be provided }

Named parameters

You can (optionally) provide the parameter names when you call a function. If you do this, you can even change the calling order!

fun repeat(s:String="*", n:Int=1):String { return s.repeat(n) } fun main() { println(repeat()) // * println(repeat(s="#")) // * println(repeat(n=3)) // *** println(repeat(s="#", n=5)) // ##### println(repeat(n=5, s="#")) // ##### }

Variable-length arguments

Finally, we can have a variable length list of arguments:

// Variable number of arguments can be passed! // Arguments in the list need to have the same type fun sum(vararg numbers: Int): Int { var sum: Int = 0 for(number in numbers) { sum += number } return sum } fun main() { sum(1) // 1 sum(1,2,3) // 6 sum(1,2,3,4,5,6,7,8,9,10) // 55 }