当我使用Scala-2.8中添加的自动生成的copy()方法时,我遇到了一些奇怪的行为。
从我读过的内容来看,当你将一个给定的类声明为一个case-class时,你会自动生成很多东西,其中一个就是copy()方法。所以你可以做以下......
case class Number(value: Int)
val m = Number(6)
println(m) // prints 6
println( m.copy(value=7) ) // works fine, prints 7
println( m.copy(value=-7) ) // produces: error: not found: value value
println( m.copy(value=(-7)) ) // works fine, prints -7
如果已经问过这个问题,我很抱歉,但这里发生了什么?
答案 0 :(得分:13)
Scala允许使用其他语言不包含的许多方法名称,包括=-
。您的参数被解析为value =- 7
,因此它正在查找=-
上不存在的方法value
。您的解决方法都会更改解析表达式的方式,以拆分=
和-
。
scala> var foo = 10
foo: Int = 10
scala> foo=-7
<console>:7: error: value =- is not a member of Int
foo=-7
^