Scala apply cannot return Option

399 Views Asked by At

I recently tried using apply like a factory function:

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

For some reason apply always returns X. Would I need to create a Factory method?

1

There are 1 best solutions below

5
Tomer Shetah On BEST ANSWER

First, you need to define apply in the companion object. Then, you need to specify specifically new X() in order to the compiler to know to use the original apply method, instead of trying to create X recursively.

case class X()

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

Code run at Scastie.