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,...