I am trying to loop a the second parameter (exp) in this function that uses call by name parameters. The first 3 parameters are the index, boolean to stop loop, and increment function. I am getting an output with 10 '()'s when I am trying to loop "hello world" 10 times as seen in the test code. May I get some help with what is wrong here? Thanks
def forLoop(ival: => Int, f: (Int) => Boolean, g: (Int)=>Int)(exp: => Unit): Unit = {
if(f(ival)==false)
return
else {
println(exp)
forLoop(g(ival),f,g)(exp)
}
}
def f(x: Int): Boolean = { x<10 }
def g(y: Int): Int = { y+1 }
val exp: Unit = "Hello World"
forLoop(0,f,g)("Hello World")
The value
"Hello World"is of typeStringhowever you are assigning it toUnitwhich compiler expands to
Note how
()becomes the value ofexp. Try changing the definition ofexptoand second parameter list to
If you compile with compiler flag
-Wvalue-discard, for example,you will get a warning