Sealed trait, case classes and companion object with pattern matching seem prevalent in Scala

They say the design pattern with sealed trait, case classes and a companion object* with functions that use pattern matching is important in Scala. I’ve seen it used in the video Tutorial: Typeclasses in Scala with Dan Rosen and a MEAP version of Functional Programming in Scala. I’ve also seen it in F#.

sealed trait MyTrait
case class AOfMyTrait (a: String) extends MyTrait
case class BOfMyTrait (b: Int) extends MyTrait

object MyTrait {
  def doSomethingWith(mt: MyTrait): Unit = mt match {
    case AOfMyTrait => // do something with an object of type AOfMyTrait
    case BOfMyTrait => // do something with an object of type BOfMyTrait
  }
}

Armed with the type definition machinery, you may now want to declare your new type as a sealed trait and create a couple of case classes so you can use the pattern matching in a companion object. It may take a while to digest them all and be confident with their proper use, but at least I know what I should learn in Scala. It makes my learning of Scala a bit more focused on what they say is really important.

[*] I seem to unable to find the document about companion object in the A Tour of Scala document. Is it there at all?

Be Sociable, Share!
This entry was posted in Languages.

3 Responses to Sealed trait, case classes and companion object with pattern matching seem prevalent in Scala

  1. anonymous says:

    Pattern matching is considered low level, instead, you should write your own combinators (e.g. catamorphism) for ADTs

  2. teamon says:

    It should at least be

    case AOfMyTrait(a) =>
    case BOfMyTrait(b) =>

Leave a Reply