Placeholder in internal functions in scala

Here is a simple code:

(0 to 20).foreach(print(math.pow(2, _)))

I was wondering why this is not working, but this similar code

(0 to 20).foreach(x => print(math.pow(2, x)))

do the job. What is the problem with using a placeholder inside an internal function?

+4
source share
1 answer

Scala uses underscores to create an anonymous function with the smallest expression that is not an identification function.

So, the compiler first tries:

(0 to 20).foreach(print(x => math.pow(2, x => x)))

No, that is an identical function, so it leaves one set of parentheses and tries:

(0 to 20).foreach(print(x => math.pow(2, x)))

This is a nontrivial anonymous function, so it stops there.

+9
source

Source: https://habr.com/ru/post/1619496/


All Articles