I'm new to Kotlin.
I was experimenting with Anonymous functions a little bit until facing different outputs for the same concept using different approaches.
- First: Creating my Anonymous function:
var greetingFunction = { playerName: String , numBuildings: Int ->
val currentYear = 2022
println("Adding $numBuildings houses")
"Welcome to SimVillage, $playerName! (Copyright $currentYear)\n"
}
- Second: Creating a function that takes another function as a parameter:
private fun runSimulation(playerName: String, greetingFunc: (String, Int) -> String){
val numOfBuildings = (1..3).shuffled().last()
println(greetingFunc(playerName, numOfBuildings))
}
A- Regular call for Anonymous function:
println(runSimulation("Ahmed", greetingFunction))
Output:
Adding 3 houses
Welcome to SimVillage, Ahmed! (Copyright 2022)
B- Shorthand call for Anonymous function:
println(runSimulation("Different") { playerName: String , numBuildings: Int ->
val currentYear = 2022
println("Adding $numBuildings houses")
"Welcome to SimVillage, $playerName! (Copyright $currentYear)\n"
})
Output:
Adding 2 houses
Welcome to SimVillage, Different! (Copyright 2022)
kotlin.Unit
I tried to remove the println() and calling the runSimulation function directly and the output was:
Output:
Adding 2 houses
Welcome to SimVillage, Different! (Copyright 2022)
What I really want to know is: how in the first place did I get that "kotlin.Unit" print using the Shorthand Syntax?
Kotlin will automatically infer the type of lambda expressions. Since the last line of
greetingFunctionis a Stringthe inferred type is
Return types for block-body functions are not inferred. If a function does not return a useful value, its return type is
Unit. The functionwill therefore return
Unit, sowill print the returned value of
runSimulation(), andUnit.toString()iskotlin.UnitSince
runSimulation()will also print to stdout, this is effectively the same as runningFirst the 'inner'
println()will outputbar, and then the 'outer'println()will printkotlin.Unit.