Alex Rivera | Logout

How to override apply in a case class companion

Asked 2011-04-29T03:25:50.943
89

So here's the situation. I want to define a case class like so:

case class A(val s: String)

and I want to define an object to ensure that when I create instances of the class, the value for 's' is always uppercase, like so:

object A {
  def apply(s: String) = new A(s.toUpperCase)
}

However, this doesn't work since Scala is complaining that the apply(s: String) method is defined twice. I understand that the case class syntax will automatically define it for me, but isn't there another way I can achieve this? I'd like to stick with the case class since I want to use it for pattern matching.

Edit
Report

1 Answer

4

Another idea while keeping case class and having no implicit defs or another constructor is to make the signature of apply slightly different but from a user perspective the same. Somewhere I have seen the implicit trick, but can“t remember/find which implicit argument it was, so I chose Boolean here. If someone can help me out and finish the trick...

object A {
  def apply(s: String)(implicit ev: Boolean) = new A(s.toLowerCase)
}
case class A(s: String)
answered 2011-04-29T07:05:56.470

Your Answer