deltanovember
deltanovember

Reputation: 44051

Why does my pattern match fail in Scala?

My method is as follows

  protected override def onEvent(event: Class[_]) = event match {
    case event: mydomain.Quote => println("qu")
    case _ => println("eventsample" + event)

  }

The console prints out the following

eventsampleclass mydomain.Quote

I thought this would have been caught in the pattern match

Upvotes: 2

Views: 313

Answers (1)

Didier Dupont
Didier Dupont

Reputation: 29528

There is no match, as your pattern is looking for an instance of Quote and your are passing classOf[Quote], which is an instance of Class[Quote], not a Quote.

To match, you would jave to call onEvent(new myDomain.Quote(...)), not onEvent(classOf[myDomain.Quote]). (It is somewhat unfortunate that the compiler accepts your first pattern, as it has no chance to match with event of type Class).

If you want to recognize class[Quote], you can use pattern case c if c == ClassOf[Quote], but I don't see any reason not to do that with a simple if/ else

Upvotes: 10

Related Questions