Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Scala case object be used in a match case

Tags:

scala

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") }
                 ^
like image 346
matanster Avatar asked Oct 07 '14 22:10

matanster


People also ask

Which method of case class allows using objects in pattern matching?

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.

What is the use of case object in Scala?

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.

What is Scala match case?

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.

How do you write a match case in Scala?

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...") }


2 Answers

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

like image 116
matanster Avatar answered Oct 12 '22 23:10

matanster


You need to specify B.type:

object something {
  val b = B
  b match { case _:B.type => println("success") }
}
like image 24
Lee Avatar answered Oct 13 '22 00:10

Lee