Hey, could there be a difference between these two lines of code ?
fun demo (name:String) = println("Hi $name")
fun demo (name:String) = "Hi $name"
I passed in both the demo functions into the HOF (High order function) and one gave result but the other did not.
This is the HOF
fun hof(name : String, myFun : (String) -> Unit)
{
println("This is my Higher Order Function")
myFun(name)
}
This is the function call:
hof("Andre", ::demo)
Here’s a runnable example:
fun demo1(name: String): Unit = println("Hi $name")
fun demo2(name: String): String = "Hi $name"
fun hof(name: String, myFun: (String) -> Unit) {
print("This is my higher order function: ")
myFun(name)
}
fun main() {
hof("Andre", ::demo1)
hof("Andre", ::demo2)
}
I made a few changes:
- Fixed the formatting
- Added explicit return types to the functions (notice
demo1
returns Unit
and demo2
returns a String
The reason you get “Hi Andre” printed for demo1
is that you’re calling demo1
. On the other hand, the demo2
function only returns a String–it isn’t printing anything to the display. Here’s a runnable example with the higher-order function removed to demonstrate:
//sampleStart
fun demo1(name: String): Unit = println("Hi $name")
fun demo2(name: String): String = "Hi $name"
fun main() {
val result1: Unit = demo1("name1") // Notice that demo1 doesn't fetch me anything but Unit. It has the side effect of printing.
println("What demo1 gave me: $result1")
val result2: String = demo2("name2") // The demo2 function fetches me the String, which I could then choose to print myself.
println("What demo2 gave me: $result2")
}
//sampleEnd
2 Likes