Understanding Kotlin Functions: Beginner’s Guide

The Major Functions In Kotlin Programming Language

One of the building blocks of a Kotlin program is functions. A function in Kotlin defines some action. In Kotlin, a function is declared using the fun keyword, followed by the function name. Then, after the name, a list of parameters is indicated in parentheses. If the function in Kotlin returns a value, you can specify the type of the returned value after the list of parameters separated by commas. And then in curly brackets is the body of the function.

What is a Function in Kotlin?

A function in Kotlin programming language is a complete section of a program that solves a specific task. Usually it is part of a large task that the program as a whole solves, although in simple cases writing a program is reduced to writing a single function. Like a function in the mathematical sense, a function in programming has inputs (parameters), an output (result), and a definition that specifies how the output value is calculated from the given input values.

Extension Functions

Let’s start with a simple one: extending classes without inheritance. We can extend this class by adding a new method or property (field), without changing the String class and all packages that use it. Let’s say we have the deleteSpaces method():

private fun String.deleteSpaces(): String {
   return this.replace(" ", "")
}

And we can use this method as if it is part of the String class.
The user will see it like this:

println("Hel lo, Wor ld".deleteSpaces()) // Hello,World

After compilation, this method will look something like this (some of the code has been simplified to make it easier for you to understand the essence):

private static final String deleteSpaces(@NotNull String receiver) {
   return receiver.replace(" ", "");
}

From this we can conclude that inside the deleteSpaces() method, we only have access to the public fields and methods of the class, so that the encapsulation is not violated. In addition to Extension Functions in Kotlin, by analogy, there can also be Extension Properties:

private val String.first: Char
    get() { 
      return this[0]
    }
print("Kotlin".first) // K

Most of the “magic” uses of functions and lambdas in Kotlin, just like this one, are nothing more than syntactic sugar, but how convenient!

Lambda Functions and Anonymous Functions

In Kotlin, anonymous and lambda functions are functions without a name, but they can be used as objects. You can write them directly inside an expression, bypassing a separate declaration.

The syntax of lambda expressions:

{ arguments -> return_type of the
function_body
}

The syntax of the anonymous function declaration is exactly the same as that of a regular function, but the first one has no name.

fun defaultFun(x: Int, y: Int): Int = x + y // Named function 
val f = fun(x: Int, y: Int): Int = x + y // Anonymous function

Higher-Order Functions in Kotlin

A higher-order function is a function that takes as one of the arguments another function, including a lambda or an anonymous function. A good example of using such functions is callback.

Let’s say we have a higher-order longWork function():

private fun longWork(callback: (arg1: Int, arg2: String) -> Unit) {
    val result = doSomething()
    callback(result, "Kotlin > Java") // call callback}

It takes the callback() function as an argument, but calls it only after the doSomething() function.

A Little More About Kotlin

Firstly, Kotlin, unlike Java, has overloaded operators. For example, if a class has a plus() method, it can be called with the + operator, and the get() method with the [] operator.

Secondly, functions in Kotlin can be explicitly marked as inline or noinline. This modifier tells the compiler whether to inline the function to increase performance or not. But here lies the catch: different behavior of return in inline and noinline functions.

In inline functions, the return will be made from the noinline function closest to the scope. In noinline – from the function itself. This problem is solved by “named return”.

To make a return from the lambda that we pass in the example above to apply(), you can use return@apply.

Not only return, but also break and continue can be named.

Appraisal

There is much more about Kotlin than what you just read. With its “magic” functions, Kotlin makes it much easier to write and, most importantly, to read code.

To learn more about Kotlin, continue reading here.


.

Recommended Articles

Share
Tweet
Pin
Share
Share