Writing functions |

Kotlin function definitions look very much like mathematical function definitions. For instance, in mathematics we would define a function \(f\) as follows

\[
f : \mathbb{Z} \times \mathbb{Z}\rightarrow \mathbb{Z},\;
f(a, b) = a + b
\]

In Kotlin, this function would be written like this
>>> fun f(a: Int, b: Int): Int = a + b >>> f(3, 9) 12Note that we have indicated the type of each parameter of the function as well as the type of the result.

The body of the function is either a single expression as in function f above, or it consists of several statements surrounded by curly braces:

fun g(a: Int, b : Int) : Int { val m = a*a - b*b val s = a - b return m/s }As mentioned above, indentation has no meaning to the Kotlin compiler at all. Nevertheless, you should indent your programs to be readable!

You have to write the name of each parameter type and the result type for a Kotlin function. (The result type can be omitted if the body of the function consists of a single expression, like in function f above.)

Like in Python, every Kotlin function returns a value. A function that does not need to return anything will return the value Unit, the only object of the type Unit, similar to the value None in Python.

So a function that returns nothing useful could be written like this:

fun greet(name : String) : Unit { println("Hello " + name) }In this case it is more common not to write the return type:

fun greet(name : String) { println("Hello " + name) }

Writing functions |