如何更正 Scala 构造函数的错误参数?

How do I correct bad arguments to a Scala constructor?

我有一个 Scala class 如图所示:

class MyClass(title: String, value: Int) {
   ...
}

如果使用 titlenull 调用构造函数,我想将 title 设置为空字符串。我怎样才能做到这一点?有没有比强制 title 私有并提供 getter?

更简洁的方法
def getTitle: String = if (title == null) "" else title

您可以创建提供所需值的工厂方法。通常,在 Scala 中,这是在伴随对象中完成的:

object MyClass {
  def apply( title: String, value: Int ): MyClass =
    new MyClass( if (title == null) "" else title, value)
}

Scala 鼓励您在值可以是 "none" 的地方使用 Option,而不是使用需要不断检查 if-not-null 的可空变量。 实现此目的的一种方法是使用辅助构造函数:

class ClassX(title: Option[String]) {
  def this(title: String) {
    this(Option(title))
  }
}

如果你必须使用一个可为空的变量,你可以使用上面提到的工厂。

就目前而言,您的 title 值只是一个构造函数参数,因此无法从外部访问它(您是否省略了 val?)。您可以使用这个事实来计算真正的 title 成员,如下所示:

class MyClass(_title: String, val value: Int) {
  val title = if (_title == null) "" else _title
  ...
}

这保证 titleMyClass

的任何情况下都不是 null

为了完整起见,这里是替代工厂方法实现:

trait MyClass {
  def title: String
  def value: Int
}

object MyClass {
  protected class MyClassImplementation(val title: String, val value: Int) extends MyClass {}

  def apply(title: String, value: Int) =
    new MyClassImplementation(if (title == null) "" else title, value)
}

创建 MyClass 实例的唯一方法是通过工厂方法,因此总是调用 null 检查。