Defining functions
Functions are defined using the fun
keyword with optional parameters and a return value. The parameter list must always be present, even if no parameters are defined. For example, this function has no parameters and it returns a String
value:
fun hello() : String = "hello world"
Each parameter is in the form name: type
. The following function accepts two parameters of the type String
and also returns a String
value:
fun hello(name: String, location: String): String = "hello to you $name at $location"
If a function does not return any meaningful value, then it is defined to return Unit
. As discussed in Chapter 2, Kotlin Basics, Unit is analogous to the Java and C void types. By using a class that is part of a type hierarchy-rather than a special type, such as void-the type system in Kotlin can be made more regular. Every function must return a value, and this value could be Unit
.
Functions returning Unit can omit the return type for procedure...