Function in Kotlin With Example

A function is a group of statement that performs a specific task. For example,

fun square(a: Int) {
   return a * a
}

Above function calculates square of any integer and return it. In similar way, every function performs a particular task.

Every kotlin program has atleast one function main(). However, you can define any number of functions in your program until memory is not full. It’s always a good practice to divide the whole program into smaller functions that are logically similar. It makes program more readable, understandable and debuggable.

A function declaration tells compiler following things about that function –
(a) Name of the function.
(b) Return type of the function.
(c) Arguments of the function (Number of arguments function accepts, Data types of the arguments, Pattern of the arguments accepted by the function).

In other words, A function declaration tells the compiler that somewhere there is a function defined with specified properties in the program.

A function definition contains the actual body of the function.

There are many inbuilt functions in kotlin standard library. For example, print(), println() etc.

Function is also known as method, subroutine or procedure etc.

There are 2 types of function in kotlin.
a. Kotlin Standard library function.
b. Kotlin User defined function.

Kotlin Standard library function

These kotlin library functions are already declared and defined in standard library. We just have to call the methods, by passing required arguments in it if any.

List of standard library functions and their task in kotlin –
print(): Prints the message to standard input and output.
println(): Prints the message to standard input and output. Then, moves the cursor to the next line.
sqrt(): Calculates the square root of a number.
dec(): Decrements the value of a number by 1.
plus(): Adds 2 values.
minus(): Subtracts one value from another value.
div(): Divides one value by another value.
plusAssign(): Adds a number (a) with another number (b) and assign the result in number a.

Above are some examples of standard library functions. However, you will get a lot more standard library functions in in standard library folder in kotlin.

Let’s see an example that demonstrates how to use standard library function in kotlin.

fun main(args: Array<String>) {

    var numb = 10
    println(numb.dec())
}

When you run the above program, you will get below output:
9

Explanation: Here, we have used a library function dec() that is used to decrement the value of number by 1. Note that println() is also a standard library function in kotlin.

Kotlin User defined function

As we have already mentioned, It is always a good habit to divide the program into smaller functions that are logically similar. In order to accomplish the task, we need to define function. A function defined by a user is called user defined function. In this section, we will learn how to create user defined function in kotlin? how to call user defined function in kotlin? Or, how to pass parameter to function? etc.

How to create user-defined function in kotlin?

Before we use/call any function in kotlin, we need to define it somewhere in the program. General form of defining a function is –

fun func_name(arguments): return_type {
function body
}

Explanation:
fun: Keyword to define the function.
func_name: Name of the user-defined function in kotlin.
arguments: List of arguments accepted by the function.
return_type: Data type of the value returned by the function. It can be Int, Float, Double, Char, Object etc.
function_body: Actual body of the function. We write codes that are logically similar in this section.
{ , } : ‘{‘ represents the starting of the body of the function. ‘}’ represents ending of the body of the function. Note that If there is only one line in the function body, we may omit ‘{‘ and ‘}’.

Let’s take an example,

fun hello(name: String): Int {
    println(name)
    return 1
}

Explanation:
fun: Keyword to define the function.
hello: Name of the function.
name: Stringname is name of the parameter being accepted by the function. String is data type of the parameter, name, that is being accepted by the function.
Int: Data type of the value being returned by the function.

Whatever is within opening (‘{‘) and closing (‘}’) brackets of the function is called body of the function.

Since we have defined the function. We will call it from another function to display the result.

How to call a user defined function in kotlin?

While creating a function, we assign some specified task that function will perform whenever it is called. Whenever a function is called, control is transferred to that function. Then, specified task is performed. After that, control is transferred back to the caller of the function. Control is transferred only when either function reaches to closing bracket ( ‘}’ ) or there is a return statement that returns from callee function to caller function.

Below image depicts the process clearly.

Tutorialwing - Calling Function in kotlin , kotlin function calling, function call in kotlin

Tutorialwing – Calling Function in kotlin

Now, we will see how to call this user defined function in kotlin to perform that specified task.

fun main(args: Array<String>) {
	
    var multipliedValue = multiply(3, 5)
    println("Multiplied value = $multipliedValue")
}

fun multiply(first: Int, second: Int) : Int {
    return first * second;
}

Explanation: Here, we have defined a function multiply() that accepts 2 integer values. Then, multiply those values and return the result. We are calling this method by it’s name (i.e. multiply()) and passing two values (3 and 5) in it that are required to call the function. Then, multiply() method is called and result is returned to the main function. The result returned form multiply() method is assigned to the variable multipliedValue. Then, This value is printed using println() method.

Actual and Formal arguments in function in kotlin

When we define a function, we mention what are the parameters that the function will accept. We also mention what are the data types of the arguments accepted by the function etc. In this section, we will learn about the the parameters associated with function.

Let’s take an example,

fun main(args: Array<String>) {
	
	val a : Int = 3
	val b : Float = 5.5f
	var multipliedValue = multiply(a, b)
	println(“Multiplied value = $multipliedValue”)
}

fun multiply(first: Int, second: Float) : Float {
    return first * second;
}

Explanation: Here, we have defined a function multiply that multiplies two numbers. It accepts two values as parameters and then multiply these two values. Then, return the result got after multiplication. We are calling this function from main() functions. After that, result returned from multiply() method is printed.
When we run the program, we will get below output:
Multiplied value = 16.5

Here, value of variable a will be assigned to variable first in multiply() function. Value of variable b will be assigned to variable second in multiply() function.

Below image clearly depicts the scenario –
Tutorialwing - Actual and formal arguments in function in kotlin

Tutorialwing – Actual and formal arguments in function in kotlin

Arguments passed to the function while calling it are called actual arguments. Here, a and b are actual arguments.
Also, Arguments defined as a parameters of the function are called formal arguments. Here, first and second are formal arguments.

Note that, data types of actual arguments must match with data types of formal arguments in same order. For example,

In the above program, we have called the function as multiply(a, b). Note that data type of a is Int while data type of b is Float. In the same order, data type of first is Int while data type of second is Float.

Note: In any function, Data type of nth actual argument must match with data type of nth formal argument.

Conclusion

In this post, we have seen how to use function in kotlin. We have seen how to use standard library function in kotlin. Also, We have seen how to create user-defined function and use them in kotlin programming langauge.

Support Us

If you have any suggestion about this post, please comment below. We are looking for someone who helps use to make our tutorial better. Also, If you want tutorials on any topic, you can mail us at tutorialwing@gmail.com. We will try to cover the topic as soon as possible. Connect with us on Facebook, Google+, Twitter and Youtube for more updates.