Signup/Sign In

Kotlin User-defined Functions

In this tutorial we will discuss about Kotlin functions, both Kotlin library functions and user-defined functions. Functions are used to break huge monolithic code into smaller pieces/chunks of code which are reusable. Ideally, we should create a function for a single task. Functions also increases code reusability as once written, the function can be called multiple times whenever required.

The functions can be of two types:

  1. Standard library functions

  2. User defined functions

Standard library functions are provided by Kotlin standard library and can be used directly. We have already used many standard library functions like: print(), println(), main(), arrayOf() etc. You can explore more about Kotlin standard library here. Now, we will see how to create user defined functions.

Kotlin User Defined Functions

As the name suggests, the user defined functions are created by users. Functions in Kotlin are created using the fun keyword. The syntax of a function is:

fun <name_of_function>(<argument_name>: <argument_data_type>):<return_type>{
    // body of the function
}

In the syntax:

  • <name_of_function>: It is the name given to the function.

  • <argument_name>: It represents the argument name.

  • <argument_data_type>: It represents the data type of the argument.

  • <return_type>: It represents the data type of value returned by the function.

For absolute beginners, arguments represents the data values supplied to the function when it is called, which are used by the function, and return type is the data type of the value that the function will return as result.

Let us create a simple function which will take an integer as input and returns the square of it:

fun getSquare(number: Int): Int {
    return number * number
}

In the code above, we have provided the data type of input argument as Int and the data type of return value also as Int.

Let us call this function from the main() function:

fun main() {
    println("The square of 9 is : ${getSquare(9)}")
}

fun getSquare(number: Int): Int {
    return number * number
}


The square of 9 is : 81

Few important points regarding functions are:

  • Once we have defined a function, we can call it as many times as we want.

  • If while calling the function, we provide wrong data type argument, then we will get a compile time exception.

  • We can also define functions which do not return anything, which we will cover in the next section of this tutorial.

Kotlin Functions that do not return anything

We can define functions which do return anything in Kotlin. There are three different ways of doing so.

Kotlin Function with no return type:

If the function is not returning anything then no need to mention the return type:

fun sayHello(){
    println("Hello World!!")
}

In the above function, we can add parameters(arguments) if we want, and still the function may not return anything. For example, we can update the getSquare() function that we defined above, to just print the result rather than returning it.

fun getSquare(number: Int) {
    println("Square is: ${number * number}")
}

Kotlin Function with Unit return type:

If we wants to specify the return type, we can add Unit as the return type for the functions which do not return anything meaningful. It is similar to void in Java. If any return type is not mentioned and any value is not returned from the function then by default return type is considered as Unit.

Let's take a code example:

fun sayHello(): Unit{
    println("Hello World!!")
}

Kotlin Function with Nothing return type:

In Kotlin, Nothing is a special type and it can also be used as the return type for the user defined functions, for the functions which returns nothing. Or, we can say, the function with Nothing as return type, never returns anything, not even the default Unit type.

For example, the below function always throws an exception:

fun exceptionEveryTime(): Nothing {
    throw IllegalArgumentException()
}

NOTE: If we call the above function in our code, then the code statement after this function call will not be executed and the compiler will show a warning.

Why can't we use Void?

You must be thinking that why cannot we use Void like in Java for Kotlin functions that do not return anything. Well, we can, but not directly.

For example,

fun setReturnTypeVoid() : Void {
    println("This function has return type as Void")
}

But this function will not be compiled and you will see the following error:


Error: Kotlin: A 'return' expression required in a function with a block body ('{...}')

You must be thinking that the function expects a return type as per the error message, so go ahead, and try adding a return null statement at the end.

fun setReturnTypeVoid() : Void {
    println("This function has return type as Void")
    return null
}

This won't work either.


Error: Kotlin: Null can not be a value of a non-null type Void

See this wouldn't work either. Why? Well because Kotlin doesn't treat Void as null type, so providing a return null statement, will give a compilation error.\

But in Kotlin, we can make a function return type nullable by using the ? operator.

For example,

fun setReturnTypeVoid() : Void? {
    println("This function has return type as Void")
    return null
}

But then, this will work with any other return type too like Int, etc. and not just for Void data type.

Summary

In this tutorial we discussed about Kotlin user defined functions. We saw why should we use functions and how to create user defined functions using the fun keyword. We learned about defining new functions with different return types. We also covered how to define function which do not return anything using the Unit and Nothing type.

We will discuss about recursion, inline functions, different types of argument in functions, lambda function etc in the coming tutorials.



About the author:
I'm a writer at studytonight.com.