Table of contents
1.
Introduction
2.
Functions
2.1.
Built-in Functions
2.2.
User-Defined Functions
2.3.
Examples
3.
How to call a User-defined function?
4.
Arguments
4.1.
Default arguments
4.2.
Named arguments 
4.3.
A variable number of arguments (varargs)
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Functions

Author Pradeep Kumar
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will look into Kotlin functions. We will see how functions are defined and invoked. If you are new to kotlin and don’t know where to start from, you can check out our other article on Getting started with Kotlin

In Kotlin, there are two types of functions: built-in functions and user-defined functions. We will also learn when and how to use both of these functions, as well as how to call them. In the next section, we will go over kotlin functions in-depth.

Functions

A function is a reusable piece of code that performs a particular task. It can be used to divide the code into smaller pieces and make it more modular. Functions can be called multiple times by executing a simple short command. Functions can be called multiple times by writing the function name followed by parentheses. If that function takes arguments, you can pass the arguments inside the parentheses as you call the function.

We use the fun keyword to declare a function in Kotlin

// Function to multiply two numbers a and b
fun multiply(a: Int, b: Int) :Int {
    return a*b
}
fun main(){
    // Calling multiply function to calculate the multiplication of 2 and 8
    var res=multiply(2,8)
    print("The Multiplication of 2 and 8 is: $res")
}

Output:

The Multiplication of 2 and 8 is: 16

The above function takes two integer arguments (i.e., a and b) and returns their multiplication as the output.

There are two kinds of functions in Kotlin:

  • Built-in function
  • User-defined function

Let’s discuss both of these in detail: 

Built-in Functions

There are various built-in functions in Kotlin that are already specified in the standard library and are ready to use. For example:

  • println(): prints the specified message/output to the screen 
  • rem(): To calculate the remainder of a number when divided by another number.

In the program below, we will use two of the most commonly used built-in functions: print() and println().

fun main() {
    println("Hey there!")
    print("Welcome to Coding Ninjas!")
}

Output:

Hey there!
Welcome to Coding Ninjas!

In the below program, we will use sqrt() function to calculate the square root of a Double number:

fun main() {
    var num=10.2 
    // Using Built-in sqrt function to calculate the square root of num
    var res= Math.sqrt(num)
    println("The Square root of ${num} is: ${res}")
}

Output:

The Square root of 10.2 is: 3.1937438845342623

Some more built-in functions and their use:

  • sum(): returns the sum of all the elements present in the given array
  • readline(): To take standard input 
  • abs(): returns the absolute value of the given number
  • max(a,b): Used to find the maximum of a and b. 
  • min(a,b): Returns the minimum value out of a and b. 
  • pow(): To calculate the power of a number raised to another number. 

User-Defined Functions

A user-defined function is one that is defined by the user. Using the keyword fun, we can define our own function in Kotlin. A user-defined function takes one or more parameters, performs an action, and returns the action's result as a value.

Generally, we define a user-defined function as follows:

fun function_name(a1: dataType, a2: dataType,....., an: dataType) : returnType {
    //Function Body
    return
}

Description of the above function is as follows: 

  • function_name: Name of the function
  • a1: dataType: an argument a1 having datatype as “dataType”. Here dataType can be Int, double, etc.
  • returnType:  Specifies the dataType of the returned value. 

Examples

A function to check if a number is even or not.

// Program to check if a number is even or not
fun isEven(a: Int) :Boolean {
    return a%2==0 // If a%2 is equal to 0, it is a even number
}
fun main(){
    var num=2
    // Calling isEven function to check if num is even or not.
    var res=isEven(num)
    print("Is $num Even? : $res") 
}

Output:

Is 2 Even? : true

Here the function isEven takes ‘a’ as an argument and returns a Boolean value.

A basic divide function which takes two arguments:

// Program to perform a basic divide operation
fun divide(a: Int, b: Int) :Int {
    return a/b
}
fun main(){
    print(divide(10,2)) // Calling divide function to calculate the division of 10 by 2
}

Output:

5

Here the divide function takes a and b as arguments and returns an integer value. 

The return type of function that doesn’t return anything is Unit.

// This function doesn’t return anything. It only prints the input value
fun print_value(a: Int) : Unit{ 
    print("Input given is: ${a}")
}
fun main(){
    // Calling print_value function to print the input value
    print_value(25)
}

Output:

Input given is: 25

Here the above print_function doesn’t return anything. As a result, the returnType is Unit. 

Note: The use of Unit as the return type is optional. If the function doesn't return anything, you may leave the term Unit. Here’s an example for the same:

// return type can be omitted in case of non-returning function
fun print_value(a: Int) {
    print("Input given is: ${a}")
}
fun main(){
// Calling print_value function to print the input value
    print_value(25)
}

Output:

Input given is: 25

How to call a User-defined function?

To call a Kotlin function, type the function’s name, then add parentheses and any parameters the function requires inside the parentheses.

// Program to perform a simple addition operation.
fun addition(a: Int, b: Int) {
    var sum=a+b
    print("sum of $a and $b is : $sum")
}
fun main(){
    addition(5,6) // Calling addition function to calculate the sum of 5 and 6.
}

Output:

sum of 5 and 6 is : 11

In the above example, we call the addition function by passing 5 and 6 as arguments.  

Arguments

An argument is a way by which you can provide some more information to a function. The function can then utilize that information while it runs. Arguments are variables that are only used in that function, and you can provide the values of an argument when you call that function. 

Functions can have different types of arguments such as:

  • Default arguments
  • Named arguments
  • A variable number of arguments (varargs)

Let’s discuss all of these in detail in the next section. 

Default arguments

Function parameters can have default values that can be used if the user skips that parameter’s value while calling the function.  

// Here the parameter a has a default value of 2
fun print_input(a: Int = 2) {
    print ("The default value of a : ${a}")
}

fun main(){
    print_input() // Calling print_input function to print the input value
}

Output:

The default value of a : 2

In the above program, the argument ‘a’ has a default value of 2. 

Named arguments 

You can name one or more arguments when calling a function. This is useful when a function has a lot of arguments.
Consider the following function, solve(), which has 3 arguments:

// This function performs a simple sum operation on all the arguments. 
fun solve(a: Int, b: Int, c: Int) {
    print(a+b+c) // prints the summation of a, b, and c
}

When calling this function, you can name zero or more arguments: 

fun main(){
    solve(a = 2, b= 3, 3) // Calling solve function to calculate the sum of all the arguments
}

Output:

8

A variable number of arguments (varargs)

We can pass a variable number of arguments using the keyword vararg. 

// This program calculates the sum of all the values passed in
// the input variable
fun calculate_sum(vararg input: Int) {
    var sum =0
    for(i in input)sum+=i //Summing all the values given in input
    println(sum)
}

fun main(){
    // Calling calculate_sum function to calculate the sum of all the values passed as arguments to the function.
    calculate_sum(1,2,3) 
    calculate_sum(1,2,3,4)
}

Output:

6
10

Must Read Elvis Operator Kotlin

FAQs

  1. Is it necessary to use the Unit keyword while defining a function that doesn’t return anything?
    No, we can omit the keyword Unit while defining a non-returning function.
     
  2. How many arguments can be passed to a function?
    You can pass any number of arguments to a function. As such, Kotlin language has no restrictions on the number of arguments, but arguments more than 8 are generally not preferred. 
     
  3. Can we have two same functions with the exact same prototype?
    No, we can not use two functions having the same function name and parameter structure in a program. Doing the same will throw errors.  

Key Takeaways

Cheers if you reached here!!!

In this blog, we learned about Kotlin Functions. We discussed different types of functions and how to call a function. We also looked at different kinds of arguments a function can take. After reading this blog, I believe you will be able to work with Kotlin functions smoothly.

Check out this article - Balanced Parentheses

Functions are extensively used with recursions to solve complex tasks elegantly. If you wish to know how to use recursion in a function, check out our article on Kotlin Recursion. And to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website. 

Live masterclass