Body of the getFunction() can be replaced with just the Green part where in the single line
● we use Lambda Expression to declare Anonymous Function
● return Closure with
○ this Anonymous Function as its Method
○ Property weight which is declared outside of the Scope of Anonymous Function
Lambda Expressions 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 USING LAMBDA EXPRESSION.
anonymousFunction = { name: String, age: Int -> "$name is $age years old and $weight kg." }
//RETURN CLOSURE WITH ANONYMOUS FUNCTION.
return anonymousFunction
//USE LAMBDA EXPRESSION DIRECTLY AS RETURN VALUE.
return { name: String, age: Int -> "$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
//USE LAMBDA EXPRESSION AS PARAMETER.
print(result)
}