Select all correct ways of using placeholder syntax in function literals.
Explanation
Sometimes when you use underscores as placeholders for parameters, the compiler might not have enough information to infer missing parameter types. For example, suppose you write _ + _ by itself:
scala> val f = _ + _
<console>:4: error: missing parameter type for expanded
function ((x$1, x$2) => x$1.$plus(x$2))
val f = _ + _
ˆ
In such cases, you can specify the types using a colon, like this:
scala> val f = (_: Int) + (_: Int)
f: (Int, Int) => Int = <function2>
scala> f(5, 10)
res9: Int = 15
Note that _ + _ expands into a literal for a function that takes two parameters. Multiple underscores mean multiple parameters, not reuse of a single parameter repeatedly. The first underscore represents the first parameter, the second underscore the second parameter, the third underscore the third parameter, and so on.
Read more: Placeholder syntax

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes