如何覆盖Scala类构造函数上的参数

时间:2015-05-15 05:37:43

标签: scala

是否可以覆盖Scala构造函数上的'val'类型?

鉴于此类:

class GPPerson (id: Option[GPID], created: Option[DateTime], active: Boolean, primaryEmail: String)

我想创建一个基本上可以执行此操作的构造函数:

if (created == None) created = new DateTime

换句话说,如果None值是耗材,请将其替换为DateTime实例。问题是,我试图避免使用伴侣对象,并且'created'对象需要'val'(不能使它成为'var')。

2 个答案:

答案 0 :(得分:2)

构造函数参数可以具有默认值:

class GPPerson (id: Option[GPID], created: Option[DateTime] = Some(new DateTime), active: Boolean, primaryEmail: String)
// to instantiate it:
new GPPerson(id = Some(id), active = false, primaryEmail = myEmail)

您可能想要重新排序参数,以便可选参数是最后一个,然后您可以省略参数名称:

class GPPerson (id: Option[GPID], active: Boolean, primaryEmail: String, created: Option[DateTime] = Some(new DateTime))
// to instantiate it:
new GPPerson(Some(id), false, myEmail)

答案 1 :(得分:1)

一种方法是

class GPPerson (id: Option[GPID], _created: Option[DateTime], active: Boolean, primaryEmail: String) {
  val created = _created.getOrElse(new DateTime)
}

另:

class GPPerson (id: Option[GPID], created: DateTime, active: Boolean, primaryEmail: String) {
  def this(id: Option[GPID], _created: Option[DateTime], active: Boolean, primaryEmail: String) = this(id, _created.getOrElse(new DateTime), active, primaryEmail)
}

虽然对于这个具体案例,我会选择@ JhonnyEverson的解决方案。