Functions in Kotlin

As in any programming language, Kotlin does support functions to be written and it enables users to write very concise functions such as the following, without any curly braces, start, and end keywords:

// This is an inline function which adds two Int values
fun add(n1: Int, n2: Int): Int = n1 + n2;

More descriptive functions with well-defined content are as follows:

/*
This is a descriptive function which adds two Double values
*/
fun add(n1: Double, n2: Double): Double {
return n1 + n2;
}

A function that doesn't return anything (effectively a procedure) can be written as follows:

fun addAndPrint(n1: Int, n2: Int): Unit {
println("$n1 + $n2 = ${n1 + n2}");
}

fun substractAndPrint(n1: Int, n2: Int) {
println("$n1 - $n2 = ${n1 - n2}");
}

This is done either by returning Unit or by completely omitting it. 

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

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