|
|
|
|
|
by DavidMcLaughlin
5491 days ago
|
|
> So, using _ in any expression makes that expression an anonymous function? Ah, I should have said - the syntax above only works with one-liners. The following wouldn't work: scala> apply(val y = _ * 50; y * 100, 10)
scala> apply((val y = _ * 50; y * 100), 10)
scala> apply((x: Int) => val y = x * 50; y * 100, 10)
etc.Instead you would need to explicitly surround the method body with curly brackets: scala> apply((x:Int) => { val y = x * 20; y }, 10)
res18: Int = 200
And in this case, it's obvious what is happening.So it's more like providing a one line expression where a function is expected makes it an anonymous function. The use of _ is simply a shortcut when you don't need to assign parameters to a local variable. It even works with multiple parameters. I.e. compare: scala> (1 to 5).foldLeft(0)((accumulator:Int,x:Int) => accumulator + x)
res22: Int = 15
To: scala> (1 to 5).foldLeft(0)(_ + _)
res19: Int = 15
|
|