Kotlin Functions

In this post, we’re talking about Kotlin functions. In high school math, we’ve studied trigonometric functions. Do you remember them? We give input to them and we obtain some output. When we give a value to sin(), it gives a result. The functions in programming are kinda the same.

Functions are blocks of statements in the program to accomplish a task. The function may or may not accept input, and it may or may not return a value as output. It all depends on our functions. We can write a function anyway as we want.

kotlin functions
kotlin-functions

The above diagram shows the flow of control when the program calls a function. On the top, we pass in value as an argument. The function starts executing and it receives the argument as function parameters. The function can use the value got as a parameter in the calculation. Finally, it returns the result, the result goes directly to the calling statement and passed to the variable on which it is assigned.

How to define functions in Kotlin?

Functions are defined in Kotlin using the keyword fun. The syntax is like this:

The function_name can be any valid identifier. The return type is the datatype of the value returned from the function.

fun function_name : returntype (parameters){
.
.
}

Types of Functions in Kotlin

1. No parameters and no return value

The function won’t accept any arguments and it won’t return any values.
Example:

fun main(args: Array<String>) {
    printName()
    println("Came back from function")

}

fun printName() {
    println("Your name")
}

Here, there are two functions. One main function and another one named printName(). The main function calls the function printName(). The program control transfers to the function. The function is executed and then the program control comes back to the main function and the next statement is executed.

2. Has parameters. No return value

It accepts arguments. We call the function with arguments. But it won’t return any value.
Example:

fun main(args: Array<String>) {
    printName("john")

}

fun printName(name:String) {
    println("Name : $name")
}

In the above program, the function printName accepts an argument of String type. We pass in a string “john” to the function. It prints a string to the screen and program control is transferred to the main function.

3. No parameters. Returns value

The function won’t accept any arguments but it will return a value at the end.
Example:

fun main(args: Array<String>) {
    val rndval = rndGen()
    println(rndval)

}

fun rndGen(): Int {
    return (Math.random() * 100).toInt()
}

The function named rndGen() is called from the main function. The function Math.random() is used to generate a random number. It generates a random number in the range 0 and 1. It’s multiplied by 100 to obtain a two digits value. Then it is converted to Int type to strip of the decimal part and obtain a whole number. Then the value is returned and assigned to the value rndval. It is printed then.

4. Has parameters. Returns value

The function accepts arguments. It returns a value as well.
Example:

fun main(args: Array<String>) {
    val num = 64.0
    val sqrRoot = sqrtCal(num)
    println(sqrRoot)

}

fun sqrtCal(n : Double): Double {
    return Math.sqrt(n)
}

We declare a double value and initialize it to 64.0. On the next line, we call the function sqrtCal() with the argument num. The function is called and passed 64.0 to its parameter. It calculates the square root of the number with the function Math.sqrt() and returns the result to the main function. The variable sqrRoot receives the returned value.

Why do we have to use functions? Well, there are a lot of benefits of using functions in program.

1. Code Reuse

We can implement a function to do some task and wherever we want to do that task in our program, we have to call it. Thus we reduce the code length. And we’re reusing the code that we’ve written again and again.

2. Code Aesthetics

The code looks beautiful when broken and modularized into various functions. Also, it will be easier for us to understand by reading the code when each task is separated into functions.

Single line functions in Kotlin

We can define functions in a really concise way in Kotlin. For example consider our earlier example program for calculating the square root of a number. We can rewrite it like this:

fun main(args: Array<String>) {
    val num = 64.0
    val sqrRoot = sqrtCal(num)
    println(sqrRoot)

}

fun sqrtCal(n : Double): Double = Math.sqrt(n)W

We define the return value after the equal symbol. It makes our functions concise and expressive.

The compiler will automatically infer the return type. So we don’t have to specify it manually. So, we can make our function even more short like this:

fun sqrtCal(n : Double) = Math.sqrt(n)

Multiple arguments

So far, the functions that we wrote accepted only one argument. It’s totally possible and it’s very likely that you’ll be writing functions that accept multiple arguments. We separate the arguments by commas. There’s no limit to the number of arguments that a function can have.

fun main(args: Array<String>) {
    printNames("John", "Jacob","Ashley")
}

fun printNames(p1:String, p2:String, p3:String) {
    println("Name1 : $p1")
    println("Name2 : $p2")
    println("Name3 : $p3")
}

Default arguments

Kotlin allows default arguments. That means, we can set the default values for arguments. So, when we call a function, the default arguments are optional. If the function call supplies the arguments, the function will take the supplied values, otherwise, it will take the default values of arguments.

fun main(args: Array<String>) {
    printNames()
    printNames("Kale")
    printNames("Kale","Kate")
    printNames("John", "Jacob","Ashley")
}

fun printNames(p1:String ="Fredrick", p2:String="Tina", p3:String="Alex") {
    println("Name1 : $p1")
    println("Name2 : $p2")
    println("Name3 : $p3")
}

Named arguments

When calling a function, we can use named arguments in Kotlin. It’s a nice feature. So, we don’t have to worry about the order of arguments.
See this example:

fun main(args: Array<String>) {
    printNames()
    printNames(p3="Kale")
    printNames(p2="Kale",p1="Kate")
    printNames(p3="John", p1="Jacob",p2="Ashley")
}

fun printNames(p1:String ="Fredrick", p2:String="Tina", p3:String="Alex") {
    println("Name1 : $p1")
    println("Name2 : $p2")
    println("Name3 : $p3")
}

Exercises

  • Write a program to calculate the sum of numbers up to n. The value of n has to get from the user. See how to get user inputs. Pass the value of n to the function. The function computes the sum and returns the result. On the main function, get the value and print the result.
  • Write a program to calculate the factorial of a number using functions

┬ź Back to the index of Kotlin tutorial´╗┐

Add a Comment

Your email address will not be published. Required fields are marked *