Functions

Functions in Kotlin are declared with the fun keyword. Following the keyword comes the function name, then parentheses, which contain optional function parameters. In Kotlin, return type comes at the end of the function definition, after a colon.

Here's a function in Kotlin that adds two numbers and returns the result:

fun add(a: Int, b: Int): Int {
val result: Int = a + b
return result
}

This function accepts two parameters of type Int (32-bit integer), has a local variable of type Int, and also returns an Int.

If you are familiar with Java, you might have noticed that types of parameters and local variables come after their name. In Java their type declaration comes first.

Calling this function would look like this:

val result: Int = add(1, 1)

In Java, every declaration, such as a field or a function, has to be inside a class. Kotlin doesn’t have such restrictions and will allow you to declare functions on a file level, outside of a class. To make it compatible with Java bytecode, a Kotlin compiler will generate a class for your file-level declarations and declare them as static members of that class.

The name of the generated class is the name of the containing file, plus the Kt suffix.

The file named FileDeclaration.kt is declared in the following command: 

fun fileLevelFunctions() {
println("I'm declared without a class")
}

If you were to call this file-level function from Java, you would need to access it as a static member of a class that a Kotlin compiler generated. This can be seen in the following command:

public class JavaClass {
public void foo() {
FileDeclarationKt.fileLevelFunction();
}
}

Kotlin also supports writing functions with expression body. In the first example, function add has a block body. Block body is everything inside the curly braces. That function can be simplified because the local variable is redundant. So, we could have written it as return a + b. In that case, we can write add function with an expression body like this:

fun addAsExpression(a: Int, b: Int): Int = a + b

You can see that the curly braces and the return keyword are dropped.

If you have a function that doesn't return a result (void function), in Kotlin you can declare it as Unit returning or omit the return type completely. The following command shows this:

fun printToConsole(input: String): Unit {
println(input)
}

No return type is also allowed and is equal to the preceding command:

fun printToConsole2(input: String) {
println(input)
}

Have you noticed that we haven't used semicolons for marking an end of a line as we would have to in Java? Semicolons are optional in Kotlin, the compiler can figure out where the line ends. In fact, you’ll get a compiler warning if you place a semicolon at the end of a line.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.236