1

由于type是保留字,因此在将其用作标识符时会附加下划线。(我找不到关于这个的风格推荐。)

val type_ = "abc"

但后来我用它作为参数标识符。

def f(id: String, type_: String, typeName: String) = Map(
    "id" -> id,
    "type" -> type_,
    "typeName" -> typeName
)

println(f("a", "simple", "test"))

但我得到一个错误

error: identifier expected but 'type' found.
def f(type: String) = 1

在两者之间放置一个空间type_:修复它

def f(id: String, type_ : String, typeName: String)

虽然这违背了推荐的 Scala 风格

这是 Scala 编译器中的错误吗?我还没有找到任何 Scala 语法的语法,所以我不能确定。

4

2 回答 2

2

在 scala 中,_in 变量名专门用于表示以下所有字符都是变量名的一部分,直到一个空格。所以在你的例子type_中是一个很好的变量名,但是当你把它放在一个方法签名中type_:时,它会推断冒号作为变量名的一部分,因为冒号和下划线之间没有空格。有关更多详细信息,您可以查看Programming Scala的第 54 页。

从书中解释,他们这样做的原因是您可以将其xyz_++=作为变量或方法名称进行操作,因为xyz++=它将被解释为 operator xyz ++=

于 2014-04-17T03:33:57.243 回答
1

When you write type_: it thinks that type_: is the name of the variable, instead of thinking that type_ is the variable name and : is a separate thing. Here's a simple example:

scala> val x_: = 2
x_:: Int = 2

scala> x_:
res0: Int = 2

scala> x_: + 3
res1: Int = 5

Putting the space in there tells the compiler that the : is not part of the variable name.

So: either keep the space, or dump the underscore.

于 2014-04-17T02:17:51.750 回答