Questions about placeholders in Scala

2019-07-07 00:28发布

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

2条回答
贪生不怕死
2楼-- · 2019-07-07 01:03

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.

查看更多
甜甜的少女心
3楼-- · 2019-07-07 01:06

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
查看更多
登录 后发表回答