Difference in singleton object with parentheses and without in pattern matching?

Viewed 46

On using even() is it so that it only matches the true condition from the unapply and on using even , how does this still prints "Is even"

object even{
  def unapply(arg: Int): Boolean = (arg%2 == 0)
}
object singleDigit{
  def unapply(arg: Int): Option[Boolean] = {
    if(arg < 10) Some(true)
    else None
  }
}
val n = 9
n match {
  case even() => println("Is even")
  case singleDigit => println("is single")
  case _ => println("No property")
}
//This gives "is single" 

n match {
  case even => println("Is even")
  case singleDigit => println("is single")
  case _ => println("No property")
}
//This gives "Is even"

How is even case satisfied here being n=9 as an odd number ? what is the difference between even and even() inside this pattern matching?

1 Answers

The case even => is actually a variable pattern and is not referring to even.unapply as hinted by compiler warning

Warning:(19, 9) patterns after a variable pattern cannot match (SLS 8.1.1)
If you intended to match against object even in class A$A3, you must use backticks, like: case `even` =>
  case even => println("Is even")
       ^

You just happened to have given it the same name, but you could write

n match {
  case foo => println("Is even")
  ...
}

and it would still print out Is even because the variable pattern is in the first position.

Related