Scala应用无法返回选项

我最近尝试使用apply像工厂函数:

class X() {
    def apply() : Option[X] = if (condition) Some(new X()) else None
}

val x : Option[X] = X() // <- this does not work; type is mismatched

出于某种原因apply 总是返回X。我需要创建一个Factory方法吗?

回答

首先,您需要apply在伴随对象中定义。然后,您需要专门指定new X()以便编译器知道使用原始apply方法,而不是尝试X递归创建。

case class X()

object X {
  def apply(): Option[X] = {
    if (Random.nextBoolean()) Some(new X()) else None
  }
}

代码在Scastie运行。

  • @JaackoTorus if the method is inside the class then you can not call it without first creating an instance of the class. If you want something like a static method then it has to be defined in the companion object.

以上是Scala应用无法返回选项的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>