Skip to content

Instantly share code, notes, and snippets.

@neko-kai
Created August 11, 2020 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neko-kai/a3a6712fef6f0c0ef1bec1cc0d73b084 to your computer and use it in GitHub Desktop.
Save neko-kai/a3a6712fef6f0c0ef1bec1cc0d73b084 to your computer and use it in GitHub Desktop.
Why you should always declare case classes final
case class X()
sealed trait Unrelated { def x: Int }
object App extends App {
def getX(xs: List[X]): List[Int] = {
xs.collect {
case u: Unrelated => u.x
}
}
}
// getX's `collect` is non-sensical, it can never match,
// but Scalac lets it through: https://scastie.scala-lang.org/68FQ2TIDSDyQJuigOHN4Ow
// However, if we declare `X` final,
// Scalac will error out on `case u: Unrelated` and prevent nonsense: https://scastie.scala-lang.org/owueF0FnQJOrCP43ugxQfQ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment