Kotlin Function: In this tutorial, you’ll learn about functions; which functions are, their syntax, and how to create a user function in Kotlin.

In programming, function is a group of related statements that play out a particular assignment.

Functions are used to break a huge program into smaller and particular pieces. For instance, you need to create and shading a circle dependent on input from the user. You can create two functions to tackle this issue:

• createCircle() Function

• colorCircle() Function

Dividing a complex program into smaller segments makes our program more coordinated and reasonable.

Moreover, it avoids redundancy and makes code reusable.


Kotlin function definition

A function is a code block containing a progression of statements. It is a decent programming practice for functions to do just a single explicit undertaking. Functions bring modularity to programs. Functions have the accompanying advantages:

  • Reducing duplication of code
  • Decomposing complex problems into simpler pieces
  • Improving clarity of the code
  • Reuse of code
  • Information hiding

A function signature is a unique identification of a function for the Kotlin compiler.. The signature comprises of a function name, its parameters, and the return type.


Types of Functions

Depending on whether a function is characterized by the user or accessible in standard library, there are two kinds of capacities:

Kotlin Standard Library Function

User-defined functions


Kotlin Standard Library Function

The standard library functions are built-in functions in Kotlin that are promptly accessible for use. For instance,

  • print() is a library work that prints messages to the standard output stream (screen).
  • sqrt() returns square root of a number (Double value)
fun main(args: Array<String>) {

    var number = 5.5
    print("Result = ${Math.sqrt(number)}")
}

At the point when you run the program, the output will be:

Result = 2.345207879911715

Here is a link to the Kotlin Standard Library for you to explore.


User-defined Functions

As referenced, you can create functions yourself. Such functions are called user-defined functions.


How to create a user-defined function in Kotlin?

Before you can use (call) a function, you need to characterize it.

Here’s the means by which you can characterize a function in Kotlin:

fun callMe() {
    // function body
}

To characterize a function in Kotlin, fun catchphrase is used. At that point comes the name of the function (identifier). Here, the name of the function is callMe.

In the above program, the bracket ( ) is vacant. That is to say, this function doesn’t acknowledge any contention. You will learn about arguments later in this tutorial.

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


How to call a function?

You need to call the function to run codes inside the body of the function. Here’s the secret:

callme()

This statement calls the callMe() function declared earlier.


Example: Simple Function Program

fun callMe() {
    println("Printing from callMe() function.")
    println("This is cool (still printing from inside).")
}

fun main(args: Array<String>) {
    callMe()
    println("Printing outside from callMe() function.")
}

At the point when you run the program, the yield will be:

Printing from callMe() function.
This is cool (still printing from inside).
Printing outside from callMe() function.

The callMe() function in the above code doesn’t acknowledge any argument.

Likewise, the function doesn’t return any worth (return type is Unit).

How about we take another function example. This function will accept arguments and furthermore returns a value.


Example: Add Two Numbers Using 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")
}

At the point when you run the program, the output will be:

result = 15

How functions with arguments and return value work?

Here, two arguments number1 and number2 of type Double are passed to the addNumbers() work during the function call. These arguments are called actual arguments..

result = addNumbers(number1, number2)

The parameters n1 and n2 accepts the passed arguments (in the function definition). These arguments are called formal arguments (or parameters).

In Kotlin, arguments are separated using commas. Additionally, the type of the formal arguments should be unequivocally composed.

Note that, the information type of actual and formal arguments should coordinate, i.e., the information sort of first actual argument should coordinate with the type of first formal argument. Also, the type of second actual argument should coordinate with the sort of second formal argument, etc.


return sumInteger

is the return statement. This code ends the addNumbers() function, and control of the program leaps to the main() function.

In the program, sumInteger is returned from addNumbers() function. This worth is assigned to the variable outcome.

Notice,

both sumInteger and result are of type Int.
the return type of the function is specified in the function definition.

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

In the event that the function doesn’t return any worth, its return type is Unit. It is discretionary to determine the return type in the function definition if the return type is Unit.


Example: Display Name by Using Function

fun main(args: Array<String>) {
    println(getName("Salman", "Khan"))
}

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

At the point when you run the program, the output will be:

Salman Khan

Here, the getName() function takes two String arguments, and returns a String.

You can exclude the curly braces { } of the function body and determine the body after = symbol if the function returns a single expression (like above example).

It is discretionary to expressly announce the return type in such case on the grounds that 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"

with

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

This is just the brief introduction to functions in Kotlin. Recommended tutorials related to functions:

  • Kotlin inline functions
  • Kotlin infix functions
  • Kotlin function scope
  • Kotlin Default and Named Arguments
  • Kotlin Recursion
  • Kotlin Tail Recursive function
  • Kotlin Extension Function
  • Kotlin High-Order Functions & Lambdas

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.