Search code examples
scalaalgebraic-data-types

Case classes match on type


If I try to match a variable on its type, like in the code below:

object CaseClassesApp extends App {

  sealed trait A{}
  final case class B() extends A{} 
  final case class C() extends A{}

  def tryMatch(x: Any): String = x match {
    case B => "It's a B!"
    case C => "It's a C!"
    case _ => "nope"
  }

  var testB = new B()
  print(tryMatch(testB))
}

Shouldn't it give me "It's a B!"? Why do I receive a "nope" instead?


Solution

  • If you want to type match, you can implement it by modifying your code just a little.

    def tryMatch(x: Any): String = x match {
      case b:B => "It's a B!"
      case c:C => "It's a C!"
      case _ => "nope"
    }