Scala 默认构造函数参数中缺少成员
下面的类有一个辅助构造函数以不变的方式更改一个属性Scala 默认构造函数参数中缺少成员,scala,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
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)}
为什么它认为没有这样的成员呢?因为它应该是这样的
class AccUnit(val size: Long, val start: Date, val direction:Direction, val 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);
}
如果您使用的是Scala 2.8,那么更好的解决方案是使用在case类上定义的copy方法,它利用了命名/默认参数功能:
case class AccUnit(size: Long, start: Date, direction:Direction, protocol:String)
val first = AccUnit(...)
val second = first.copy(size = 27L)
最后一句我想是不正确的,他们是会员,但他们是私人的。scala>class AccUnit(size:Long,start:Date,direction:direction,protocol:String){override def toString=“size:”+size+”,start:“+start}scala>new AccUnit(1,new Date(),new direction(),“test”)res2:AccUnit=size:1,start:Tue Oct 19 20:37:44 CEST 2010如果它们在类的主体中使用,它们将自动成为成员:)嗯,WFT。。。啊哈。。。你有任何关于doc的参考资料吗?“Scala中的编程”中的第6.5章查看了Scala参考,但我没有看到一个清晰的语句。或许可以在scala用户邮件列表中询问?
case class AccUnit(size: Long, start: Date, direction:Direction, protocol:String)
val first = AccUnit(...)
val second = first.copy(size = 27L)