Preventing a class instantiation in Scala using Factory Pattern -
this question has answer here:
suppose have following class defined in scala:
class classa(val n: int) { ... }
i want limit class instances have n between 5 10 using factory pattern. example, in case write like:
val = new classa(11)
this raises exception appropriate error message, or @ least returns null or something. how can achieve behaviour?
update:
it possible achieve in java with factory pattern.
update2:
this questions seems answered here, notably verbose title though. tweak title , content save question being deleted, because of 2 reasons: 1) example in 1 concise, 2) provided answer @chris martin explains briefly way factory pattern can reached in scala using companion objects.
the conventional way write factory in scala define apply
method on companion object.
here's example using either
(because null
never/rarely used in scala, , exceptions ugly):
class private (n: int) { override def tostring = s"a($n)" } object { def apply(n: int): either[string, a] = if (n < 5) left("too small") else if (n > 10) left("too large") else right(new a(n)) } a(4) // left(too small) a(5) // right(a(5)) a(11) // left(too large)
this same java example referenced. a
constructor private, class can instantiated via factory method.
Comments
Post a Comment