Learning Kotlin – Part 6

This time we look at functions.
Let’s take a simple function from Java:

public int mult(int num1, int num2){
    return num1 * num2;
}

In Kotlin it would look like this:

fun mult(num1: Int, num2: Int): Int{
    return num1 * num2
}
  • A function definition always starts with the keyword fun. That’s fun isn’t it?
fun mult
  • A function is public per default so no need for the public keyword
  • The types of the argument are written behind the argument  name separated by a colon which looks similar to Python’s type hints
fun add(num1: Int, num2: Int)
  • The function’s return type is added after the arguments
fun mult(num1: Int, num2: Int): Int {
  • And last but not least a function has a body:
fun mult(num1: Int, num2: Int): Int { 
    return num1 * num2 
}

Single expression functions

When the function body returns a single expression, you can leave out the cruly braces:

fun add(num1: Int, num2: Int): Int = num1 + num2