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

时间:2010-10-19 17:29:16

标签: 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)}
}

编译器返回错误:

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)}

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

2 个答案:

答案 0 :(得分:7)

因为它应该是

class AccUnit(val size: Long, val start: Date, val direction:Direction, val protocol:String) {...}

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

在您的版本中,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);
}

答案 1 :(得分:6)

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

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

val first = AccUnit(...)
val second = first.copy(size = 27L)