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?
First, you need to define
applyin the companion object. Then, you need to specify specificallynew X()in order to the compiler to know to use the originalapplymethod, instead of trying to createXrecursively.Code run at Scastie.