Kotlin Tutorial - 5 Function

nadirbasalamah

nadirbasalamah

Posted on October 5, 2021

Kotlin Tutorial - 5 Function

When creating a program or software, functions is usually used to make a code become resuable and easy to read. In Kotlin, there are two main types of function including void function and a function that returns a value.

Void Function

Void function is a function that does not return any values. In Kotlin, a void function is also known as a function that returns Unit type.

This is the basic syntax of creating void function.

fun function_name(arg_name: data_type, ...) {
    // code ..
}
Enter fullscreen mode Exit fullscreen mode

In this example, the sum() function is created to perform sum operation of two integers.

fun main() {
    // call the sum function with given parameters
    sum(12,24)
}

// create a sum function
// with two integers as the arguments
fun sum(numOne: Int, numTwo: Int) {
    println("$numOne + $numTwo = ${numOne + numTwo}")
}
Enter fullscreen mode Exit fullscreen mode

Output

12 + 24 = 36

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the sum() function using two integers (numOne and numTwo) as the arguments. The sum() function is called inside main function with given parameters.

The default argument value can be added inside function, this is the example of a function with default argument value.

fun main() {
    // call the greet function without parameter
    greet()
}

// create a greet function
// with default argument
// the default argument value is "guest"
fun greet(name: String = "guest") {
    println("Hello, $name !")
}
Enter fullscreen mode Exit fullscreen mode

Output

Hello, guest !
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the default argument value is used if the parameter inside the function is not specified.

Function with Return Value

In Kotlin, the function that created can also returns certain value. This is the basic syntax of creating a function with return value.

// multi line
fun function_name(arg_name: data_type, ...): return_type {
    // code ..
}

// single line
fun function_name(arg_name: data_type, ...) = // code..
Enter fullscreen mode Exit fullscreen mode

In this example, the multiply() and average() function is created.

fun main() {
    // call the multiply function with given parameters
    val result = multiply(12,24)
    println("The result of multiply operation: $result")

    // call the average function with given parameters
    val averageResult = average(78,90,80,67)
    println("The average result: $averageResult")
}

// create a multiply function
// using single line approach
// with two integers as the arguments
fun multiply(numOne: Int, numTwo: Int) = numOne * numTwo

// create a average function
// with variadic argument of integer as the argument
fun average(vararg nums: Int): Int {
    var result = 0
    for (num in nums) {
        result += num
    }
    return result / nums.size
}
Enter fullscreen mode Exit fullscreen mode

Output

The result of multiply operation: 288
The average result: 78

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the multiply() function contains single line of code so the single line approach is used. This is the multiply() function with multi line approach.

fun multiply(numOne: Int, numTwo: Int): Int {
    return numOne * numTwo
}
Enter fullscreen mode Exit fullscreen mode

On the code above, the average() function is also created with variadic argument of integers using vararg followed with argument's name and argument's data type.

The variadic argument (vararg) also avaiable for void function.

Overloading Functions

Overloading functions is a function with the same name but with the different arguments. This is the example of overloading mechanism for area() function.

fun main() {
    // call the functions
    println("area of circle: ${area(7.0)}")
    println("area of rectangle: ${area(8.0, 9.0)}")
}

// calculate area of circle
fun area(radius: Double) = Math.PI * radius * radius

// calculate area of rectangle
fun area(length: Double, width: Double) = length * width


Enter fullscreen mode Exit fullscreen mode

Output

area of circle: 153.93804002589985
area of rectangle: 72.0
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the function has a same name called area() but with different arguments.

Infix Function

Infix function is a function that can be called without parentheses (). This is the basic syntax to create an infix function.

infix fun receiver_type.func_name(arg): return_type {
    // code..
}
Enter fullscreen mode Exit fullscreen mode

There are many rules to follow when creating an infix function:

  1. Variadic argument is not allowed.
  2. The function must have one argument.
  3. The function type is a member or extension function.

Member function is a function that created inside class. Extension function is a function that is extended from a certain function inside library.

This is the usage example of infix function.

// create a class called Person
class Person(
    val name: String
) {
    // create an infix function
    infix fun say(message: String) {
        println("$name says $message")
    }
}

fun main() {
    // create an object from Person class
    val person: Person = Person("ray krieger")

    // call an infix function with parentheses
    person.say("hi there!")

    // call an infix function without parentheses
    person say "this is fantastic"
}

Enter fullscreen mode Exit fullscreen mode

Output

ray krieger says hi there!
ray krieger says this is fantastic

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the infix function is a member function inside Person class. The infix function can be called with or without using parentheses.

Lambda

Lambda is an anonymous function that can be used in Kotlin. This is the basic syntax to create a lambda in Kotlin.

{ parameter,... -> // code }
Enter fullscreen mode Exit fullscreen mode

This is the usage example of lambda.

fun main() {
    // create a lambda function
    val multiply = { a: Int, b: Int -> a * b }

    // call a lambda function
    val result: Int = multiply.invoke(2,3)

    // print out the result
    println("The result is: $result")
}

Enter fullscreen mode Exit fullscreen mode

Output

The result is: 6

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the lambda function is created inside multiply variable. The lambda function is called using invoke() method from variable that store lambda function.

The usage of lambda function can be seen in method usage for Collections like map() method.

fun main() {
    // create a collection
    val list = listOf<Int>(1,2,3,4,5)

    // using lambda inside map method
    // to multiply every number inside collection with 3
    val updatedList = list.map { num -> num * 3 }

    // print out the result from map
    println("Result from map")
    updatedList.forEach { num -> println(num) }
}
Enter fullscreen mode Exit fullscreen mode

Output

Result from map
3
6
9
12
15

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the lambda function that used inside map method is { num -> num * 3 } to multiply every number inside collection with 3.

Higher-order Function

Basically, higher-order function is a mechanism that a function is available to become argument or parameter in another function or a function could return another function or callback.

This is the usage example of higher-order function.

fun main() {
    // create a lambda function
    // that will be inserted as parameter in calculator function
    val operator = { a: Int, b: Int -> a + b }

    // call a calculator function with parameter
    val result = calculator(4,5, operator)

    // print out the result
    println("The result is: $result")

}

// create a calculator function with these arguments:
// 1. x and y with Int data type
// 2. operator is a function with two integer arguments that returns integer "(Int, Int) -> Int"
fun calculator(x: Int, y: Int, operator: (Int, Int) -> Int): Int {
    // returns the result of lambda function execution
    // that stored inside operator argument
    return operator.invoke(x,y)
}
Enter fullscreen mode Exit fullscreen mode

Output

The result is: 9

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the calculator function is created with many arguments including x and y with Int data type and operator is a function type that has two Int arguments with return type is Int. The calculator function is called inside main method with specified parameters.

Recursive Function

Recursive function is a function that called itself. Recursive function can be used to solve many problems like fibonacci number calculation.

This is the example of using recursive function to solve fibonacci calculation.

fun main() {
    // call the fib function
    println(fibonacci(5))
}

fun fibonacci(n: Int): Int {
    if(n <= 2)
        return 1
    else
        return fibonacci(n - 1) + fibonacci(n - 2)
}
Enter fullscreen mode Exit fullscreen mode

Output

5
Enter fullscreen mode Exit fullscreen mode

Based on the code above, there are two main components inside recursive function:

  • Base case: is a case or condition that define when the recursive function is stopped. The base case inside that function is if the value of n is less than or equals 2.

  • Recursive case: is a case or condition that define when the certain code is executed until the base case. The recursive case inside that function is to sum two previous numbers (fibonacci(n - 1) + fib(n - 2)).

This is the illustration of how the recursive function works.

Recursive function

Notes

  • In Kotlin, the parameter's name inside function can be defined. This is the example.
fun main() {
    // call a function with parameter's name
    val result = plus(x = 3, y = 9)
    // print out the result
    println(result)

}

// create a function
fun plus(x: Int, y: Int): Int {
    return x + y
}
Enter fullscreen mode Exit fullscreen mode

Output

12
Enter fullscreen mode Exit fullscreen mode

Sources

  • Learn more about function in this link.

  • Learn more about infix function in this link.

  • Learn more about lambda in Kotlin in this link.

  • Learn more about higher-order function in this link.

I hope this article is helpful for learning the Kotlin programming language. If you have any thoughts or comments you can write in the discussion section below.

πŸ’– πŸ’ͺ πŸ™… 🚩
nadirbasalamah
nadirbasalamah

Posted on October 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related