关于 Scala 中占位符的问题
考虑 Scala 中的以下定义:
val f = ((_: Int) + 1).toString()
代码将函数文字 _ + 1 的字符串表示形式分配给 f,这很自然,只是这不是我想要的。我打算定义一个函数,它接受 int 参数,将其加 1,并返回其字符串格式。
为了消除歧义,我必须编写一个带有显式参数的 lambda 表达式:
val g = (x: Int) => (x + 1).toString()
那么我是否可以得出占位符语法不适合复杂函数文字的结论? 或者是否有一些规则规定了函数文字的范围?似乎占位符不能嵌套在函数文字中的括号中(定义其类型所需的除外)
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您认为占位符语法除了简单的函数文字之外没有用处,这是正确的。
就其价值而言,您提到的特定情况可以使用占位符语法和函数组合的结合来编写。
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.
这是正确的。请参阅占位符语法和用例示例。
This is correct. See the rules for the placeholder syntax and a use case example.