Here is the simple code:
(0 to 20).foreach(print(math.pow(2, _)))
I was wondering, why it doesn't work, but this similar code
(0 to 20).foreach(x => print(math.pow(2, x)))
do work. What's the problem with using the placeholder inside the inner function?
Scala uses underscores to create an anonymous function with the smallest expression that isn't the identity function.
So the compiler first tries:
(0 to 20).foreach(print(x => math.pow(2, x => x)))
Nope, that's the identity function, so it goes out one set of parentheses and tries:
(0 to 20).foreach(print(x => math.pow(2, x)))
That is a nontrivial anonymous function, so it stops there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With