62

According to scala-wartremover static analysis tool I have to put "final" in front of every case classes I create: error message says "case classes must be final".

According to scapegoat (another static analysis tool for Scala) instead I shouldn't (error message: "Redundant final modifier on case class")

Who is right, and why?

1 Answer 1

113

It is not redundant in the sense that using it does change things. As one would expect, you cannot extend a final case class, but you can extend a non-final one. Why does wartremover suggest that case classes should be final? Well, because extending them isn't really a very good idea. Consider this:

scala> case class Foo(v:Int)
defined class Foo

scala> class Bar(v: Int, val x: Int) extends Foo(v)
defined class Bar

scala> new Bar(1, 1) == new Bar(1, 1)
res25: Boolean = true

scala> new Bar(1, 1) == new Bar(1, 2)
res26: Boolean = true
// ????

Really? Bar(1,1) equals Bar(1,2)? This is unexpected. But wait, there is more:

scala> new Bar(1,1) == Foo(1)
res27: Boolean = true

scala> class Baz(v: Int) extends Foo(v)
defined class Baz

scala> new Baz(1) == new Bar(1,1)
res29: Boolean = true //???

scala> println (new Bar(1,1))
Foo(1) // ???

scala> new Bar(1,2).copy()
res49: Foo = Foo(1) // ???

A copy of Bar has type Foo? Can this be right?

Surely, we can fix this by overriding the .equals (and .hashCode, and .toString, and .unapply, and .copy, and also, possibly, .productIterator, .productArity, .productElement etc.) method on Bar and Baz. But "out of the box", any class that extends a case class would be broken.

This is the reason, you can no longer extend a case class by another case class, it has been forbidden since, I think scala 2.11. Extending a case class by a non-case class is still allowed, but, at least, in wartremover's opinion isn't really a good idea.

4
  • 8
    Wow, that indeed sounds like a mess! How comes they didn't prevent also case class to class inheritance, since it presents very similar problems?
    – sscarduzio
    Jan 2, 2016 at 11:06
  • 5
    @sscarduzio: it is because of source compatibility. As it was explain to me (twitter.com/viktorklang/status/735556776989491201), such a modification would imply a major version increment, which does not seem to be planned by lightbend for now (or for that at least).
    – fanf42
    Jun 14, 2016 at 8:47
  • @Dima, I have scala 2.12 but it's still allowing case class to be extended.
    – tintin
    Nov 3, 2018 at 20:07
  • 4
    @tintin Yes, you can (still) extends a case class, but not with another case class
    – Dima
    Nov 4, 2018 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.