Functions in Kotlin are declared using the fun keyword
fun main(args: Array<string>) {
// code here
}
How to add parameters in function declaration:
Function parameters are defined using Pascal notation, i.e. name: type. Parameters are separated using commas. Each parameter must be explicitly typed:
fun multiple(number: Int, exponent: Int) { … }
How to add default arguments in function declaration:
Default values are defined using the = after type along with the value.
fun multiple(b: Int, c: Int = 0, d: Int = 10) { … }
return type Unit:
If a function does not return any useful value, its return type is Unit. Unit is a type with only one value – Unit. This value does not have to be returned explicitly:
fun printHello(name: String): Unit {
if (name != null)
println("Hello ${name}")
else
println("Hi there!")
// return Unit or return is optional } The Unit return type declaration is also optional. The above code is equivalent to: fun printHello(name: String) { … }
Single-Expression functions:
When a function returns a single expression, the curly braces can be omitted and the body is specified after a = symbol:
fun double(x: Int): Int = x * 2