1

I wrote the following code:

class MyActor extends Actor {
  override def receive: Receive = {
    case p: Set[String] => //
  }
}

But when compiling the following warning is emitted:

Warning:(22, 13) non-variable type argument String in type pattern 
scala.collection.immutable.Set[String] (the underlying of Set[String]) 
is unchecked since it is eliminated by erasure
    case p: Set[String] =>

Why? Is there a way to get rid of it except supressing?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

1

You can't really pattern match on anything with a type parameter, this is by design, since the JVM runtime does not have the notion of type parameters at runtime.

Easiest thing to do is wrap it in a value class.

case class StringSet(val value: Set[String]) extends AnyVal

Then you can easily pattern match on it:

override def receive: Receive = {
  case StringSet(p) => //
}
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
  • There are factual errors here. First, value classes *do in fact get instantiated at runtime when you do a pattern match*. Second, `StringSet` needs to be a case class--or you need to define an `unapply` in the companion object of `StringSet`--if you want to pattern match on it. But on the bright side, you identify type erasure as the issue and correctly point out that pattern matching on constructors rather than types is the way to go. – Vidya Mar 22 '17 at 16:14