Reputation: 878
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?
Upvotes: 4
Views: 464
Reputation: 8539
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.
Upvotes: 6