Function getFunction() actually returns a Closure with
● this Anonymous Function as its Method
● Property weight which is declared outside of the Scope of Anonymous Function
When you compare this code with Lambda Expressions as Function Parameter you see that it is as compact while
● allowing us to specify Data Type of Return Value
● use normal return
● use Syntax that is similar to Named Function Declarations (unlike Lambda that uses completely different Syntax)
Lambda Expressions as Return Value
return { name: String, age: Int -> "$name is $age years old and $weight kg." }
Function as Return Value
//===========================================================================================================
// FUNCTION: getFunction
//===========================================================================================================
fun getFunction (weight: Int) : (name: String, age: Int) -> String {
//DECLARE VARIABLE TO HOLD FUNCTION DATA TYPE.
var anonymousFunction : (name: String, age: Int) -> String
//DECLARE ANONYMOUS FUNCTION.
anonymousFunction = fun (name: String, age: Int) : String {
return "$name is $age years old and $weight kg."
}
//RETURN ANONYMOUS FUNCTION.
return anonymousFunction
//USE ANONYMOUS FUNCTION DECLARATION DIRECTLY AS RETURN VALUE.
return fun (name: String, age: Int) : String { return "$name is $age years old and $weight kg." }
}
//===========================================================================================================
// FUNCTION: main
//===========================================================================================================
fun main() {
//DECLARE VARIABLE TO HOLD FUNCTION DATA TYPE.
var returnedFunction : (name: String, age: Int) -> String
//DECLARE ANONYMOUS FUNCTION USING LAMBDA EXPRESSION.
returnedFunction = getFunction(150) //Returns Closure with partialy initialized Function
//CALL RETURNED FUNCTION.
var result = returnedFunction("John", 20) //Call Function with missing Parameters
//DISPLAY RESULT.
print(result)
}