scala - How to override apply in a case class companion -
so here's situation. want define case class so:
case class a(val s: string)
and want define object ensure when create instances of class, value 's' uppercase, so:
object { def apply(s: string) = new a(s.touppercase) }
however, doesn't work since scala complaining apply(s: string) method defined twice. understand case class syntax automatically define me, isn't there way can achieve this? i'd stick case class since want use pattern matching.
the reason conflict case class provides exact same apply() method (same signature).
first of suggest use require:
case class a(s: string) { require(! s.tochararray.exists( _.islower ), "bad string: "+ s) }
this throw exception if user tries create instance s includes lower case chars. use of case classes, since put constructor out when use pattern matching (match
).
if not want, make constructor private
, force users only use apply method:
class private (val s: string) { } object { def apply(s: string): = new a(s.touppercase) }
as see, no longer case class
. not sure if case classes immutable fields meant modification of incoming values, since name "case class" implies should possible extract (unmodified) constructor arguments using match
.
Comments
Post a Comment