缺少默认构造函数参数的成员

Bas*_*evs 2 scala

以下类具有辅助构造函数,以不可变的方式更改一个属性.

class AccUnit(size: Long, start: Date, direction:Direction, protocol:String) {
    def this(size:Long, that:AccUnit) {this(size, that.start, that.direction, that.protocol)}
}
Run Code Online (Sandbox Code Playgroud)

编译器返回错误:

AccUnit.scala:26: error: value start is not a member of trafacct.AccUnit
        def this(size:Long, that:AccUnit) {this(size, that.start, that.direction, that.protocol)}
                                                           ^
AccUnit.scala:26: error: value direction is not a member of trafacct.AccUnit
        def this(size:Long, that:AccUnit) {this(size, that.start, that.direction, that.protocol)}
                                                                       ^
AccUnit.scala:26: error: value protocol is not a member of trafacct.AccUnit
        def this(size:Long, that:AccUnit) {this(size, that.start, that.direction, that.protocol)}
Run Code Online (Sandbox Code Playgroud)

为什么会这样认为,没有这样的成员?

Ale*_*nov 7

因为它应该是

class AccUnit(val size: Long, val start: Date, val direction:Direction, val protocol:String) {...}
Run Code Online (Sandbox Code Playgroud)

要么

case class AccUnit(size: Long, start: Date, direction:Direction, protocol:String) {...}
Run Code Online (Sandbox Code Playgroud)

在您的版本中,size其他只是构造函数参数,而不是成员.

更新:您可以自己检查:

// Main.scala
class AccUnit(size: Long, protocol: String)

F:\MyProgramming\raw>scalac Main.scala

F:\MyProgramming\raw>javap -private AccUnit
Compiled from "Main.scala"
public class AccUnit extends java.lang.Object implements scala.ScalaObject{
    public AccUnit(long, java.lang.String);
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*ght 6

如果您使用的是Scala 2.8,那么更好的解决方案是使用在案例类上定义的复制方法,它利用了命名/默认参数功能:

case class AccUnit(size: Long, start: Date, direction:Direction, protocol:String)

val first = AccUnit(...)
val second = first.copy(size = 27L)
Run Code Online (Sandbox Code Playgroud)