Reputation: 61
I have a quite simple Scala code where I wanted to apply pattern matching:
trait Expr
case class Number(n: Int) extends Expr
case class Sum(a: Expr, b: Expr) extends Expr
case class Prod(a: Expr, b: Expr) extends Expr
def eval(e: Expr): Int = e match
case Number(n) => n
case Sum(a, b) => eval(a) + eval(b)
case Prod(a, b) => eval(a) * eval(b)
But when I run the code the error rises: "Number cannot be used as an extractor in a pattern because it lacks an unapply or unapplySeq method"
What should I do to avoid this error? Thank you
Upvotes: 2
Views: 1182
Reputation: 488
Apparently it's true what was said before, that java.lang.Number
shadows case class Number
when run in IntelliJ. If you don't want to abandon your IDE, you can also rename case class Number
to case class Num
. This way, the code runs fine at least on my machine.
Upvotes: 0
Reputation: 15115
You probably have imported java.lang.Number
in the scope of the eval
definition.
Make sure to import your Number
definition instead (either by removing the Java import or renaming it, whatever fits best your use case...) and it will work fine.
Upvotes: 2