(+91) 113 551 1687 contact@syncsas.com New Delhi

Single Expression Functions, “vararg” & Spread Operator

Usually, a function must declare its return type; an exception exists only for functions that consist of a single expression. These are often referred to as one line or single line functions. Such functions can use a shortened syntax that omits the braces and uses the = symbol before the expression rather than the return keyword.

Single-Expression Functions
Kotlin allows you to reduce the amount of code required to define a function like castFireball or formatHealthStatus that has only one expression – that is, one statement to be evaluated. For single-expression functions, you can omit the return type, curly braces, and return statement. Make those changes to your castFireball and formatHealthStatus functions, as shown below:

In Kotlin, functions are first-class citizen. It means that functions can be assigned to the variables, passed as an arguments or returned from another function. While Kotlin is statically typed, to make it possible, functions need to have a type. It exists and it is called function type. Here are a few examples:
()->Unit —the function type that returns nothing useful (Unit) and takes no arguments.
(Int)->Int— the function type that returns Int and takes single argument of type Int.
()->()->Unit— the function type that returns another function that returns nothing useful (Unit). Both functions take no arguments.
Function type is just a syntactic sugar for an interface, but the interface cannot be used explicitly. Nevertheless we can use function types like interfaces, what includes using them as type arguments or implementing them: