Functions Structure in Kotlin

In programming, functions are where the program's behaviour and logic are normally defined.
Aready we've seen a simple function's syntax in our hello world example. You declare a function using the fun keyword followed by the identifier. You can then optionally pass a list of parameters in the parantheses.
Below are two example types of functions:

Function Returning Nothing.
fun main(args: Array<String>){
    println("Hello World")
}

RESULT

Hello World
Function Returning Value.
fun older(age1: Int, age2: Int): Int{
    return if(age1>age2) age1 else age2
}

>>> println(older(10,20))
20
>>>
Things we learn from the above examples:
  1. Functions in kotlin are declared using the fun keyword.
  2. We can pass a list of parameters to the function by listing them in the parameters separated by comma.
  3. Once we've closed the parantheses of the function identifier, we specify a colon then the return type. fun older(age1: Int, age2: Int): Int.
  4. In kotlin, if constructs are expressions and not statements. This means they have a value. So the above if(age1>age2) age1 else age2 actually returns a value either age1 or age2. This is similar to java's ternay operator : (age1 > age2) ? age1 :age1 .

Expression Bodies in Kotlin

Kotlin language emphasises on code conciseness.Thus the above example can be simplified further to just a single line of code by removing the return statement and curly braces.
The function examples we saw earlier are said to have block body. The below example has an expression body. A function is said to have an expression body if it returns an expression directly.

fun older(age1: Int, age2: Int): Int = if (age1 > age2) age1 else age2

EXAMPLE

fun main(args: Array<String>) {
    //print older age
    println(older(23,56))
}
fun older(age1: Int, age2: Int): Int = if (age1 > age2) age1 else age2

RESULT

56

EXAMPLE

fun main(args: Array<String>) {
    //print older age
    println(older(23,12))
}
fun older(age1: Int, age2: Int): Int = if (age1 > age2) age1 else age2

RESULT

23

Remarkably, the above function can even be simplified further by removing the return type.

fun older(age1: Int, age2: Int) = if (age1 > age2) age1 else age2

The Kotlin compiler can automatically determine the return type from the expression body.