Questions about placeholders in Scala

纵饮孤独 提交于 2019-12-12 13:21:53

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/9051909/questions-about-placeholders-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!