4

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?

Jaacko Torus
  • 796
  • 7
  • 24

1 Answers1

6

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.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
  • Thank you, this made it work. So I shouldn't put the `apply` method in the class in favor of the object? (Just to be clear) – Jaacko Torus May 26 '21 at 17:34
  • 2
    @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. – Luis Miguel Mejía Suárez May 26 '21 at 17:37