Functions in Kotlin

You are here:
Estimated reading time: 5 min

In this tutorial, we will be learning how to use functions in Kotlin. We will also be covering the following topics:

  • Classification of functions based on definition and scope.
  • Default and Named arguments in Kotlin
  • Unit Returning functions
  • Single Expression functions
  • Variable Arguments in Kotlin – vararg
  • Spread Operator and vararg in Kotlin

In programming, a function is a named section of reusable code that performs a specific task.

Classification of Functions in Kotlin

Classification based on Definition

  • Standard Library functions/Built-in functions – These are predefined functions. They are a part of the language itself.
  • User-defined functions – These are created by the programmers, as per their needs.

Classification based on the scope within which the function is defined

  • Top-Level Functions: These do not need a class to be enclosed in.
  • Member Functions: These are defined inside a class or object.
  • Local or Nested Functions: Functions that are defined inside another function.

Functions as First-Class Citizens

Functions in Kotlin are first-class citizens, which means that they can be stored in variables and data structures, passed as arguments to other functions as well as returned from other functions. (Functions that take other functions as parameters or return a function, are known as Higher-Order Functions)

Syntax

Functions in Kotlin have 4 parts:

  • Function Name – This is the name of the function. The function name followed by parentheses () is used to call a function. For example – “add()” will call the function named “add” for execution.
  • Parameter List – When a function is called/invoked, some values are passed to it. These are known as parameters or arguments. Function parameters are optional, i.e. a function may have no parameters at all.
  • Function Body – The set of statements to be executed when a function is invoked.
  • Return Statement – A function may return a value to its calling function. This value is known as a return value. The value to be returned is preceded by the “return” keyword. For example, “return a+b” will return the sum of a and b.

Functions in Kotlin are declared using the fun keyword.

fun functionName (param1Name:param1Type, param2Name:param2Type,..) : returnType{
    //function body
    return returnValue
}

The fun keyword is followed by the name of the function.

The parentheses () contains the parameter list. Each parameter is written in the format parameterName:parameterDataType and different parameters in the list are separated by commas (,).

The parameter list is followed by a : followed by the return type of the function. The return type may be Int, Double, etc.  The function body is written inside curly braces {}. The return statement is written as the return keyword followed by the return variable/expression/value.

Declarations and Usage

Top-Level Functions

fun main(){
    var x : Int = 4
    var y : Int = 6
    var result : Int
    result = productOfTwo(x,y)
    println(result)
}
fun productofTwo(a:Int , b:Int):Int{
    var product = a*b
    return product
}

Member Functions

fun main(){
    var num1 = 4
    var num2 = 5
    var result : Int
    var x = DemoClass()
    result = x.productOfTwo(num1,num2)
    println(result)
}
class DemoClass{
    fun productOfTwo(a:Int , b:Int):Int{
        return a*b
    }  
}

Member functions are defined inside a class.

Here the function productOfTwo is a member function defined inside the class DemoClass.

A member function is called as objectName.functionName().

Here, x is an object of the DemoClass and the function productOfTwo is called as x.productOfTwo().

Nested Functions

Functions can also be defined inside other functions. These are known as Nested functions.

fun main(){
    var num1 = 4
    var num2 = 5
    var result : Int
    result = productOfSquares(num1,num2)
    println(result)
}
fun productOfSquares(a:Int , b:Int):Int{
    fun squaredNumber(z:Int) : Int{
        return z*z
    }
    var aSquared = squaredNumber(a)
    var bSquared = squaredNumber(b)
    return aSquared+bSquared
}  

Actual and Formal Parameters

fun main(){
    var x = 4
    var y = 5
    var result : Int
    result = addNumbers(x,y)
    println(result) //will print 9
    changeNumbers(x,y)
    println(x) //will print 4
    println(y) //will print 5
}
fun addNumbers(a:Int,b:Int) : Int{
    return a+b
}
fun changeNumbers(a:Int,b:Int) : Unit{
    a = 9
    b = 15
}

In the above example, x and y are called actual parameters.

Actual parameters/arguments are the variables defined inside the calling function. In this case, main() is the calling function.

The parameters defined in the parameter list are known as Formal parameters. These are like photocopies of the actual parameters.

Note:

  • The data type of actual parameters and formal parameters must be the same.
  • The data type of the returned variable and the data type of the variable that the function is equated to should be the same.

When calling the function addNumbers, the values x and y are passed as parameters.

The value of x is copied to the formal parameter a and the value of y is copied to the formal parameter b.

Note: The order of the variables in the function call is important. If the function call in the above example was addNumbers(y,x) instead of addNumbers(x,y), then the value of y will be stored in the formal parameter a and the value of x will be stored in the formal parameter b.

The function addNumbers is returning the sum of a and b which is being stored in the variable “result” in the main function.

If a function is returning a value, then it must be part of an expression.

In the function changeNumbers, the value of x is stored in a and the value of y is stored in b. The function changeNumbers changes the value of a to 9 and b to 15.

But, after the function is executed completely, the value of x and y will remain the same in the main function i.e. x will still be 4 and y will still be 5. This is because Changes in the formal parameters are not reflected in the values of the actual parameters.

Default Arguments in Kotlin

Kotlin allows us to set default values of the arguments in the function definition. Therefore, if an argument is not passed in the function call, it’s default value will be used.

fun main(){
    var num1 = 9
    var result : Int
    result = productOfTwo(num1)
    println(result)
}
fun productOfTwo(a:Int = 6 , b:Int = 5):Int{
    return a*b
}  

Here the default values for function parameters a and b are 6 and 5 respectively.

In the function call, only one value is passed. This value will replace the default value of the formal parameter a. Therefore, the new value of a will be 9. Since no argument is passed for the formal parameter b, it’s default value 5 will be used.

Named Arguments in Kotlin

Kotlin allows us to set the argument passed to the function to its respective formal parameter.

This way, it is not necessary to pay attention to the order in which the arguments are passed to a function.

fun main(){
    var num1 = 9
    var num2 = 8
    var num3 = 7
    var num4 = 3
    var result : Int
    result = sumOfFour(b=num2, a=num1, d=num4, c=num3)
    println(result)
}
fun sumOfFour(a:Int, b:Int, c:Int, d:Int):Int{
    return a+b+c+d
}  

Unit Returning Functions

If the function doesn’t return anything, the return type used is Unit (equivalent to void in Java, C, etc.).

In the above example, the function changeNumbers is a Unit returning function.

It is optional to specify the return type in the function definition if the return type is Unit.

fun changeNumbers(a:Int,b:Int) : Unit{
    a = 9
    b = 15
}
fun changeNumbers2(a:Int,b:Int){
    a = 9
    b = 15
}

The functions changeNumbers and changeNumbers2 are the same.

Single Expression Functions

The curly braces {} of the function body can be omitted if the function returns a single expression. Instead, the function body can simply be specified after an = sign.

fun addNumbers(a:Int,b:Int) : Int{
    return a+b
}
fun addNumbers2(a:Int,b:Int) : Int = return a+b

In the above example, the functions addNumbers and addNumbers2 are the same.

Also, in such a case where a function returns a single expression, it is optional to explicitly declare the return type of the function, because it can be inferred by the compiler.

fun addNumbers3(a:Int,b:Int) = return a+b

Therefore, all the 3 functions addNumbers, addNumbers2 and addNumbers3 are the same.

Variable Number of Arguments – vararg

In many cases, it is not possible to determine the number of arguments to be passed to a function. Kotlin supports declaring functions that can have variable number of arguments.

In such a case, vararg is used.

The vararg keyword is written before the parameter name in the parameter list.

fun functionName(vararg param:paramType):returnType{
    //function body
    return returnValue
}

As opposed to Java, the vararg parameter does not have to be the last in the parameter list. But, only one vararg parameter is allowed in the parameter list of a function.

fun main(){
    var result : Int
    result = sumOfAny(1,2)
    println(result)
    result = sumOfAny(1,2,3)
    println(result)
    result = sumOfAny(1,2,3,4)
    println(result)
    result = sumOfAny(1,2,3,4,5,6,7,8,9)
    println(result)
}
fun sumOfAny(vararg nums:Int):Int{
    var sum : Int = 0
    for (i in nums){
        sum+=i
    }
    return sum
}  

Spread Operator and vararg

The spread operator is represented by an asterisk in Kotlin (*).

The spread operator in Kotlin unpacks an array into values of the array.

Therefore, an array can be passed to a vararg parameter in a function using the spread operator.

fun main(){
    var numbers = intArrayOf(5,10,15,20)
    var result : Int
    result = sumOfAny(*numbers,1,2,3,4)
    println(result)
}
fun sumOfAny(vararg nums:Int):Int{
    var sum : Int = 0
    for (i in nums){
        sum+=i
    }
    return sum
}  

Examples

Function to print first and last name

fun main(){
    var fname :String = "Peter"
    var lname :String = "Parker"
    printName(fname,lname)
}
fun printName(a:String , b:String){
    println("Hello, $a $b! Welcome to kotlintutorials.com!")
}

Function having different types of parameters

fun main(){
    var name :String = "Peter"
    var salary :Int = 12000
    var score :Double = 4.5
    var grade :Char = 'B'
    printDetails(name,salary,score,grade)
}
fun printDetails(a:String , b:Int , c:Double , d: Char){
    println("Hello, $a! Welcome to kotlintutorials.com!")
    println("Here are your details:")
    println("Salary: $b\nScore: $c\nGrade:$d")
}

Read more about Named and Default Arguments in Kotlin

Other articles:

Extension in Kotlin

Arrays in Kotlin

Kotlin v/s Java

References:

https://kotlinlang.org/docs/reference/functions.html

Was this article helpful?
Dislike 0
Views: 8