How to create functions in Kotlin?

Kotlin has some nice improvements compared to Java in how you can define a function.

First, create a function named multiply that accepts two integer parameters and returns integer value the product of the two parameters. Let's create it with a block body:

fun multiply(a: Int, b: Int): Int {
    return a * b
}

Now we can create a new function with the same parameters and name it multiply2, but now we use expression body instead of block body:

fun multiply2(a: Int, b: Int) = a * b

You can use the expression body of a function when the function body consists of one expression.

 

Comments powered by CComment