Can a Scala case object be used in a match case?
E.g. this does not work:
abstract class A
case object B extends A
object something {
val b = B
b match { case _:B => println("success") }
}
not found: type B
b match { case _:B => println("success") }
^
The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches.
A case object is like an object , but just like a case class has more features than a regular class, a case object has more features than a regular object. Its features include: It's serializable. It has a default hashCode implementation.
It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C. Here, “match” keyword is used instead of switch statement.
Using if expressions in case statements i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + a) case c if 20 to 29 contains c => println("20-29 range: " + a) case _ => println("Hmmm...") }
Oops, seems that this also compiles:
abstract class A
case object B extends A
object something {
val b = B
b match { case B => println("success") }
}
Scala Fiddle: Can a Scala case object be used in a match case
You need to specify B.type
:
object something {
val b = B
b match { case _:B.type => println("success") }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With