Tutorials

The Absolute Beginner’s Guide to Kotlin Programming

The Major Functions In Kotlin Programming Language

Kotlin program is founded of various sets of functions. A function in Kotlin determines some action and is declared using the fun keyword, followed by the name. After the name, comes a list of parameters indicated in parentheses. If the function in Kotlin returns a value, you can identify the type of the returned value after the list of parameters divided by commas. And then in curly brackets comes the body of the function.

Defining Functions in Kotlin

A function in Kotlin programming language could be described as a complete section of a program that is designed to solve a particular task. Typically it is part of a bigger task that the program as a whole completes, although in simple cases writing a program is decreased to scripting a single function. Similar to a function in the mathematical terms, a function in programming has inputs (parameters), an output (result), and a statement that regulates how the output value is calculated from the given input values.

Extension Functions

We could start with the simplest one: extending classes without inheritance. This class could be extended by adding a new method or property (field), without modifying the String class and all packages that use it. Let’s imagine we have the following deleteSpaces method():

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

And this method could be used as a part of the String class.
The user will observe it in the following pattern:

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

Once the compilation is over, this method will look something like this (some of the code has been optimized to make it easier for you to see the essence):

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

From this we can summarize that inside the deleteSpaces() method, we only have access to the public fields and methods of the class, so that the encapsulation is not completely disregarded. Additional to Extension Functions in Kotlin, in correlation, there can also be Extension Properties:

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

Most of the “magic” application of functions and lambdas in Kotlin, just like this one, are nothing more than syntactic sequence, yet very convenient one.

Lambda and Anonymous Functions Described

In Kotlin, anonymous and lambda functions are functions that do not have a name, but can be applied as objects. It is possible to insert them directly in an expression, bypassing a separate declaration.

The basic syntax of lambda expressions goes like this:

{ arguments -> return_type of the
function_body
}

The syntax of the anonymous function declaration looks exactly the same as the regular function, but the first one does not have a 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 Described

A higher-order function is a function that treats another function (lambda or an anonymous function) as one of the arguments. A good illustration of using such functions is callback.

Let’s imagine 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 activates it only after the doSomething() function.

About Kotlin

To start with, Kotlin, unlike Java, contains overloaded operators. For instance, if a class has a plus() method, it can be activated with the + operator, and the get() method with the [] operator.

Another thing is that functions in Kotlin can be explicitly marked as inline or noinline. This modifier regulates the compiler to inline the function to increase performance or not. Yet there is a nuance to it: different pattern of return in inline and noinline functions.

In inline functions, the return will be completed via the noinline function closest to the scope. In noinline – from the function itself. This complication could easily be solved by “named return”.

In order to make a return from the lambda that we pass in the example above to apply(), you should add return@apply.

Keep in mind that not only return, but also break and continue can be named.

Summary

There is much more to learn about Kotlin than you have just read here. With its great variety of functions, Kotlin makes it much simpler to script and work with code.

 


.

You may also like...