0

If someone could explain this behavior in plain english I would really appreciate it. Specifically, is there any difference between case _:Foo and case Foo()?

myvariable match {
  case _: Foo => println("its a foo!")
  case Foo() => println("It's also a Foo")
  case Foo => println("Oops, this will *not* match a Foo! It will never be called")
  case _ => println("This will be called for all unmatched items")
}

1 Answer 1

4

This is a normal type match, sort of like a instanceOf in Java for example.

case x: Foo => ???

It guarantees that you can use x as a Foo on the right hand side

case Foo(a,b,c) => ???

On the other hand tries to call unapply (which you get for free on a case class) and allows you to "reach into" the instance and catch all fields as vals that you can use on the right hand side.

Side note: defining a case class with no fields is essentially identical to using a case object, which is what most people do in Scala to just represent one possible value. So your second case is a bit strange, and would probably rather be done using case objects:

case object Foo

case Foo => ???
3
  • Ahhh I get it now, case Foo() is actually calling Foo.unapply, but because it's an empty parameter list there's nothing to extract. I know the third case is a bit odd, but I think it's a common mistake so I wanted to include it as an "oops" for others reading
    – Hamy
    Sep 20, 2014 at 18:06
  • 1
    @Hamy The third case is not odd at all -- you do this when you want to match a value, rather than a structure. So if you have a case of a sealed trait that doesn't carry any data, as johanandren alluded to, you could make it a case object and match it that way. You can also match literal values that way too. There's another type of case too which uses backticks to match against a previously defined variable.
    – acjay
    Sep 21, 2014 at 0:37
  • @acjay - Sure, all great advice. Perhaps odd was the wrong word, I meant that I believe people often confuse case Foo with case Foo(), not realizing that the former is probably not doing what they intended. For example, see stackoverflow.com/questions/2254710/… where the first answer mentions this confusion
    – Hamy
    Sep 21, 2014 at 1:27

Your Answer

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

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