How to create functions in Kotlin?

Kotlin has some nice improvements compared to Java in defining 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 start 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.

Function without return value

If the function does not have a return value, you omit the return type in the function declaration:

fun sayHello() {
    println("Hello!")
}

Unlike in Java, you have to provide "void" to indicate that message does not return a value.

If the function is defined with an expression

fun sayHelloFromExpression() = println("Hello from expression!")

 

 

Comments powered by CComment