Defining functions in Kotlin

In Kotlin, functions are declared using the fun keyword. The following code snippet shows an example:

fun helloBasic(name: String): String {
return "Hello, $name!"
}

Function arguments are specified in brackets after the function name. name is an argument of the String type. The function return type is specified after the arguments. The return type of the function is String.

The following line of code shows the invocation of the helloBasic function:

println(helloBasic("foo")) // => Hello, foo!

Kotlin also allows names to be added. The following line of code shows an example:

println(helloBasic(name = "bar"))

Function arguments can optionally have a default argument value:

fun helloWithDefaultValue(name: String = "World"): String {
return "Hello, $name!"
}

The following line of code shows the invocation of the helloWithDefaultValue function without specifying any parameters. The default value of the name argument is used:

println(helloWithDefaultValue()) //Hello, World

If a function has just one expression, then it can be defined on a single line. The helloWithOneExpression function is a simplified version of the helloWithDefaultValue function. The return type is inferred from the value:

fun helloWithOneExpression(name: String = "world") = "Hello, $name!"

Functions returning void and having only one expression can also be defined on a single line. The following code snippet shows an example:

fun printHello(name: String = "world") = println("Hello, $name!")
..................Content has been hidden....................

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