In this tutorial you will learn about Functions, including different types of functions and their implementation via simple practical step by step examples.

Step 1: Create Project

  1. Open your favorite Kotlin IDE.
  2. In the menu go to File --> Create New Project.

Step 2: Add Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Our code will comprise the following Kotlin files:

Example 1: Inline Functions

Let us look at a simple Inline Functions example written in Kotlin Programming Language. Follow the following steps:

  1. In your editor or IDE, create a file known as Inline.kt.
  2. Then add the following code:

(a). Inline.kt

package Functions.Inline

// You can inline functions to improve performance of your code.
// The reference says inlining works best for functions with lambda parameters.
@Suppress("NOTHING_TO_INLINE")
inline fun sayHello(number : Int) {
    println("hello world $number")
}

public fun main(args : Array<String>) {
    (1..10).forEach {
        sayHello(it)
    }
}

Step 4: Run

Copy the code, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 2: Function Literals

  1. In your editor or IDE, create a file known as Literals.kt.
  2. Then add the following code:

(a). Literals.kt

package Functions.Literals

fun main(Args : Array<String>) {

    //this is how to declare it and assign it to a value - since the type is specified,
    // you can omit the type declration in the implementation
    val literal : (String) -> Unit = { println(it) }
    literal("This will be printed")

    //A statement literal - notice you have to declare the type of the parameter
    val literal2 = { x : String -> println(x.toUpperCase()) }
    literal2("This is all uppercase now")

    //A function literal  - notice you have to declare the tyep of the parameter but you can omit the return type
    var literal3 = { x : String -> x.toLowerCase() }
    var lowercases = literal3("THIS IS ALL LOWERCASE NOW")
    println("$lowercases")

    //A function literal that uses multiple lines
    var literal4 = {
        x : String ->
        var y = "Multiple lines: " + x
        y //you have put the variable to be returned since return keyword is not allowed here
    }

    var text = literal4("What a wonderful world")
    println("$text")

    fun show(p : (String) -> Unit) {
        p("This is a function literal")
    }

    show({ x -> println(x) }) //this is a function literal - a one off function

    //you can also have a function literal without a parameter
    fun show2(p : () -> Unit) {
        p()
    }

    show2({ println("This is a function literal without a parameter") })

    //and if the last parameter of a function is a parameter, you can pass it outside ()
    show2 { println("See, we are passing this function literal outside the ()") }
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 3: Local Function

  1. In your editor or IDE, create a file known as LocalFunction.kt.
  2. Then add the following code:

(a). LocalFunction.kt

package Functions.LocalFunction

public fun main(args : Array<String>) {
    fun localFunction() {
        println("I am a local function")
    }

    //you can call a local function
    localFunction()

    fun localFunction2(func : () -> Unit) {
        func()
    }

    //you can pass a local function to a lambda parameter by using a reference to a function
    localFunction2(::localFunction)
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 4: Local class

  1. In your editor or IDE, create a file known as LocalClass.kt.
  2. Then add the following code:

(a). LocalClass.kt

package Functions.LocalClass

fun main(Args : Array<String>) {
    class AirForce(val name : String)

    val usa = AirForce("USA")
    val india = AirForce("India")

    println("${usa.name} and ${india.name}")
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 5: Function Parameters

  1. In your editor or IDE, create a file known as Parameters.kt.
  2. Then add the following code:

(a). Parameters.kt

package Functions.Parameters

//primitive parameters (String, Int, Float, etc) is passed by value so you cannot change the value of the passed parameter
fun primitives(name : String) {
    //name = "John Adams"
}

//object references are also passed by value (which means you cannot change the object itself - check complex2 function) but since it is an object reference,
//you can change the value inside the object
fun complex(p : Person) {
    p.firstName = "John"
    p.lastName = "Adams"
}

data class Person(var firstName : String, var lastName : String) {

}

fun main(Args : Array<String>) {
    var president = "JFK"
    println("President name is $president")
    primitives(president)
    println("Now the President is $president")

    var president2 = Person("John", "Kennedy")
    println("President name is ${president2.firstName} ${president2.lastName}")
    complex(president2)
    println("Now the is ${president2.firstName} ${president2.lastName}")

    var president3 = Person("John", "Kennedy")
    println("President name is ${president3.firstName} ${president3.lastName}")
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 6: Named Arguments

  1. In your editor or IDE, create a file known as NamedArguments.kt.
  2. Then add the following code:

(a). NamedArguments.kt

package Functions.NamedArguments

fun superHeroCapabilities(
        name : String,
        fly : Boolean = false,
        swim : Boolean = false,
        punch : Boolean = true
) {

    if (fly)
        print ("$name can fly ")
    else
        print ("$name cannot fly ")

    if (swim)
        print (", can swim ")
    else
        print (", cannot swim ")

    if (punch)
        print ("and can punch")
    else
        print ("and cannot punch")

    println("")
}

fun main(Args : Array<String>) {
    var batman = superHeroCapabilities(name = "Batman")
    var superman = superHeroCapabilities(name = "Superman", fly = true)
    var hulk = superHeroCapabilities(name = "Hulk", punch = true)
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 7: Operator Overloading

  1. In your editor or IDE, create a file known as OperatorOverloading.kt.
  2. Then add the following code:

(a). OperatorOverloading.kt

package Functions.OperatorOverloading

fun main(Args : Array<String>) {

    var batman = SuperPower()
    batman.say()
    +batman
    batman.say()
    -batman
    batman.say()

    var robin = SuperPower()
    robin.say()
}

public class SuperPower() {
    var power : Int = 1
    var action = "Neutral"
    operator fun unaryPlus() {
        power++
        action = "+"
    }

    operator fun unaryMinus() {
        power--
        action = "-"
    }

    fun say() {
        println(action + " " + power)
    }

    override fun toString() : String = "$power"
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 8: Last Function Parameter

  1. In your editor or IDE, create a file known as LastFunctionParameter.kt.
  2. Then add the following code:

(a). LastFunctionParameter.kt

package Functions.LastFunctionParameter

fun main(Args : Array<String>) {
    doCalculation {
        y ->
        if (y > 10)
            y + 10
        else
            y + 20
    }
}

fun doCalculation(calc : (Int) -> Int) {
    print("This is the result ${calc(10)}")
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 9: Extensions

  1. In your editor or IDE, create a file known as Extensions.kt.
  2. Then add the following code:

(a). Extensions.kt

package Functions.Extensions

fun String.glorify() {
    println("You are amazing " + this)
}

fun String.insults(count : Int) {
    println("${this}, you are ${count} times dumber than a dog")
}

public fun main(args : Array<String>) {
    "John".glorify()
    "John".insults(3)
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 10: Extensions As Parameter

  1. In your editor or IDE, create a file known as ExtensionsAsParameter.kt.
  2. Then add the following code:

(a). ExtensionsAsParameter.kt

package Functions.ExtensionsAsParameter

public fun main(args : Array<String>) {
    //this refers to Robot instance
    var typeA = configurator {
        this.canFight()
        this.canFly()
    }

    typeA.show()

    //if the last parameter is a function, the function literal can be passed outside the parantheses
    //'this' is also optional in any case of extension function.
    var typeB = configurator ({
        canSwim()
        canFly()
    })

    typeB.show()

    var typeC = configurator("Mayora") {
        canSwim()
    }

    typeC.show()
}

fun configurator(config : Roboto.() -> Unit) : Roboto {
    var r = Roboto()
    r.config()
    return r
}

fun configurator(name : String, config : Roboto.() -> Unit) : Roboto {
    var r = Roboto()
    r.giveName(name)
    r.config()
    return r
}

public class Roboto {
    var capabilities = ""
    var name = ""

    fun giveName(name : String) {
        this.name = name
    }

    fun canSwim() {
        capabilities += "Can Swim \n"
    }

    fun canFight() {
        capabilities += "Can Fight \n"
    }

    fun canFly() {
        capabilities += "Can Fly \n"
    }

    fun show() {
        if (name != "")
            println ("$name can $capabilities")
        else
            println (capabilities)
    }
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 11: Single Expression Function

  1. In your editor or IDE, create a file known as SingleExpression.kt.
  2. Then add the following code:

(a). SingleExpression.kt

package Functions.SingleExpression

//we are using single expression function
//this also demonstrate the ability to have function within function
fun main(Args : Array<String>) {
    fun sayHello(name : String) = "Hello $name"

    fun triple(number : Int) = number * 3

    for (x in 1..triple(2)) //we are using a range here
        println(x.toString() + "." + sayHello("Adam"))
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 12: Tail Recursive functions

  1. In your editor or IDE, create a file known as TailRecursive.kt.
  2. Then add the following code:

(a). TailRecursive.kt

package Functions.TailRecursive

//make recursive functions safer (won't blow the stack)
tailrec fun loop(current : Int = 0, until : Int) {
    if (current < until) {
        print("$current ")
        loop(current + 1, until)
    }
    else
        print("Finished")
}

fun main(Args : Array<String>) {
    loop(until = 10)
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 12: it Variable

  1. In your editor or IDE, create a file known as ItVariable.kt.
  2. Then add the following code:

(a). ItVariable.kt

package Functions.ItVariable

fun main(Args : Array<String>) {
    val primeNumbers = arrayOf(1, 2, 3, 5, 7, 11)

    primeNumbers.forEach({ x -> println(x) })

    println("they are equivalent")

    primeNumbers.forEach ({ println(it) })

}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 13: Lambda Function

  1. In your editor or IDE, create a file known as Lambda.kt.
  2. Then add the following code:

(a). Lambda.kt

package Functions.Lambda

//this is a tricky section. Pay attention

fun main(Args : Array<String>) {
    val xline : (String) -> String = { y : String -> "Full " + y }
    println("Full format function literal '${xline("Moon")}'")

    val xline2 : (String) -> String = { y -> "Short " + y }
    println("Shortened function literal '${xline2("Sticks")}'")

    doMore(xline2)
    doMore({ y -> "Literal Function " + y })

    doMore({ y ->
        var m = y + " multiline"
        m
    })

    doCalculation({
        y ->
        var m = y + 10
        m
    })
}

fun doMore(doSomething : (String) -> String) {
    println("This is from passed function '${doSomething("Great")}'")
}

fun doCalculation(calc : (Int) -> Int) {
    print("This is the result ${calc(10)}")
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 14: Infinix Function

  1. In your editor or IDE, create a file known as Infix.kt.
  2. Then add the following code:

(a). Infix.kt

package Functions.Infix

public fun main(args : Array<String>) {
    //using a function
    val say = "Hello " add "world" //infix function call
    println(say)

    val say2 = "Hello ".add("world 2")
    println(say2)

    //using a method
    val hello = HelloWorld()
    var say3 = hello say "world 3"
    println(say3)

    var say4 = hello.say("world 4")
    println(say4)
}

infix fun String.add(more : String) : String = this + more

class HelloWorld() {
    infix fun say(more : String) : String {
        return "Hello " + more
    }
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 15: Closure

  1. In your editor or IDE, create a file known as Closure.kt.
  2. Then add the following code:

(a). Closure.kt

package Functions.Closure

fun main (Args : Array<String>){
    var number = 1

    fun incrementAndShow(){
        number++
        println(number)
    }

    for(x in 1..3)
        incrementAndShow()
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Example 16: Function Cascade

  1. In your editor or IDE, create a file known as Cascades.kt.
  2. Then add the following code:

(a). Cascades.kt

package Functions.Cascades

fun main(Args : Array<String>) {
    /* This call utilizes extension function and infix call. It is handy to deal with pesky Java object initializations */
    var superman = Superman() with {
        name = "Lux Luthor"
        punch()
        kick()
        sidekick = Spiderman() with {
            special()
        }
    }
}

public infix fun <T> T.with(operations : T.() -> Unit) : T {
    operations()
    return this
}

public class Superman() {
    var name : String = "Clark Kent"
    var sidekick : Sidekick = Robin()

    public fun punch() : Unit = println("$name punches")
    public fun fly() : Unit = println("$name flies")
    public fun kick() : Unit = println("$name kicks")
}

interface Sidekick {
    public fun special()
}

public class Spiderman() : Sidekick {
    var name : String = "Peter Parker"
    override fun special() = println("$name webs")
}

public class Robin() : Sidekick {
    var name : String = "Robin"
    override fun special() = println("$name is useless")
}

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Step 4: Run

Copy the code, build and run.