关于Scala中的占位符的问题 [英] Questions about placeholders in Scala

查看:106
本文介绍了关于Scala中的占位符的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中考虑以下定义:

Consider the following definition in Scala:

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

代码将f表示函数文字_ + 1的字符串表示形式,这很自然,只不过这不是我想要的.我打算定义一个接受int参数,将其递增1并返回其字符串格式的函数.

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.

要消除歧义,我必须编写一个带有显式参数的lambda表达式:

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

这篇关于关于Scala中的占位符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆