One way of defining a function as an object is by using anonymous functions. They work the same way as normal functions, but they have no name between the fun keyword and the parameter declaration, so by default they are treated as objects. Here are a few examples:
val a: (Int) -> Int = fun(i: Int) = i * 2 // 1 val b: ()->Int = fun(): Int { return 4 } val c: (String)->Unit = fun(s: String){ println(s) }
- This is an anonymous single-expression function. Note that, as in a normal single expression function, the return type does not need to be specified when it is inferred from the expression return type.
Consider the following usage:
// Usage println(a(10)) // Prints: 20 println(b()) // Prints: 4 c("Kotlin rules") // Prints: Kotlin rules
In the previous examples, function types were defined...