Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placeholder in inner functions in scala

Tags:

scala

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?

like image 304
Mikhail Avatar asked Jan 07 '23 00:01

Mikhail


1 Answers

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.

like image 183
drhagen Avatar answered Jan 16 '23 06:01

drhagen