문제

Consider the following definition in Scala:

val f = ((_: Int) + 1).toString()

The code assigns to f the string representation of the function literal _ + 1, which is quite natural, except that this is not i want. i intended to define a function that accepts an int argument, increments it by 1, and returns its string format.

To disambiguate, i have to write a lambda expression with explicit parameters:

val g = (x: Int) => (x + 1).toString()

So can i conclude that the placeholder syntax is not suitable for complex function literals? Or is there some rule that states the scope of the function literal? It seems placeholders cannot be nested in parentheses(except the ones needed for defining its type) within the function literal

도움이 되었습니까?

해결책

Yes, you are right in thinking that placeholder syntax is not useful beyond simple function literals.

For what it's worth, the particular case you mentioned can be written with a conjunction of placeholder syntax and function composition.

scala> val f = ((_: Int) + 1) andThen (_.toString)
f: Int => java.lang.String = <function1>

scala> f(34)
res14: java.lang.String = 35

다른 팁

It seems placeholders cannot be nested in parentheses(except the ones needed for defining its type) within the function literal

This is correct. See the rules for the placeholder syntax and a use case example.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top