English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Functions

In this article, you will learn about functions. What is a function, its syntax, and how to create user-defined functions in Kotlin.

In programming, a function is a set of related statements that perform a specific task.

Functions are used to break down large programs into smaller modular blocks. For example, if you need to create circles based on user input and color them, you can create two functions to solve this problem:

  • createCircle() function - Used to create circles

  • colorCircle() function - Used to fill color

Dividing complex programs into smaller components can make our programs more organized and easier to manage.

In addition, it avoids repetition and makes the code reusable.

Function type

There are two types of functions depending on whether they are user-defined functions or standard library functions:

  • Kotlin standard library functions

  • User-defined functions

Kotlin standard library functions

Standard library functions are built-in functions in Kotlin that can be used at any time. For example,

  • The print() function is a library function that can print messages to the standard output stream (monitor).

  • The sqrt() function returns the square root of a number (Double value)

fun main(args: Array<String>) {
    var number = 5.5
    print("Result = ${Math.sqrt(number)}")
}

When running the program, the output is:

Result = 2.345207879911715

This isKotlin Standard Librarylink for you to browse.

User-defined functions

As mentioned earlier, you can create your own functions. These functions are called user-defined functions.

How to create user-defined functions in Kotlin?

Before using (calling) a function, you need to define it first.

Here is how to define a function in Kotlin:

fun callMe() {
    //Function body
}

To define a function in Kotlin, use the fun keyword. Then comes the name of the function (Identifier). Here, the name of the function is callMe.

In the above program, the parentheses ( ) are empty. This means the function does not accept any parameters. You will learn about parameters in the later part of this article.

The code inside the curly braces { } is the body of the function.

How to call a function?

You must call this function to run code within the function body. Here's how to do it:

callme()

This statement calls the previously declared function callMe().

Example: Simple function program

fun callMe() {
    println("Printing from the callMe() function.")
    println("That's cool (still printing from inside).")
}
fun main(args: Array<String>) {
    callMe()
    println("External printing from the callMe() function.")
}

When running the program, the output is:

Printing from the callMe() function.
That's cool (still printing from inside).
External printing from the callMe() function.

The callMe() function in the above code does not accept any parameters.

Additionally, the function does not return any value (return type is Unit).

Let's look at another function example. This function will accept parameters and return a value.

Example: Adding two numbers using a function

fun addNumbers(n1: Double, n2: Double): Int {
    val sum = n1 + n2
    val sumInteger = sum.toInt()
    return sumInteger
}
fun main(args: Array<String>) {
    val number1 = 12.2
    val number2 = 3.4
    val result: Int
    result = addNumbers(number1, number2)
    println("result = $result")
}

When running the program, the output is:

result = 15

How do functions with parameters and return values work?

Here, during the function call, two Double type parameters number1and number2Passed to the addNumbers() function. These parameters are called actual parameters (or actual parameters).

result = addNumbers(number1, number2)

Parameter n1and n2Accept the passed parameters (in the function definition). These parameters are called formal parameters (or formal parameters).

In Kotlin, parameters are separated by commas. Similarly, the type of the formal parameters must be explicitly typed.

Note that the data types of the actual parameters and formal parameters should match, that is, the data type of the first actual parameter should match the type of the first formal parameter. Similarly, the type of the second actual parameter must match the type of the second formal parameter, and so on.

Here,

return sumInteger

is a return statement. This code terminates the addNumbers() function, and the program control jumps to the main() function.

In the program, sumInteger is returned from the addNumbers() function. This value has been assigned to the variable result.

Note that,

  • sumInteger and result are both of type Int.

  • The return type of the function is specified in the function definition.

    //The return type is Int
    fun addNumbers(n1: Double, n2: Double): Int {
        ... .. ...
    }

If a function does not return any value, its return type is Unit. If the return type is Int, it can be specified in the function definition.

Example: Displaying a name using a function

fun main(args: Array<String>) {
    println(getName("John", "Doe"))
}
fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

When running the program, the output is:

John Doe

Here, the getName() function accepts two String parameters and returns a String.

If a function returns a single expression (as shown in the example above), the curly braces {} of the function body can be omitted, and the subject is specified after the = symbol.

In this case, explicitly declaring the return type is optional because the return type can be inferred by the compiler. In the above example, you can replace

fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

It is equivalent to:

fun getName(firstName: String, lastName: String) = "$firstName $lastName"

This article is a brief introduction to functions in Kotlin.