Functions in Kotlin

In this post I will talk about 5 cool things that functions can do in Kotlin, better than methods in Java.

  1. Forget about overloaded methods

In Java, when you need the same method to have 1 parameter in one case and more parameters in another case, you would have to overload the method. This means to write another method with the same name, but different parameters. In Kotlin, this is history. You can provide default values for parameters, which are used when you do not provide all the corresponding arguments.

  • Java

    Kotlin

     

2. A function can have as a parameter another function

A function that takes another function as parameter is called Higher-Order function.

3. We can create a function inside another function

A function that is created inside another function is called local function.

4. We can create functions without name

A function that does NOT have a name, is called an anonymous function

5. We can use lambdas

A lambda function is a simpler way of representing an anonymous function.