Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
模式匹配scala与集合_Scala_Collections - Fatal编程技术网

模式匹配scala与集合

模式匹配scala与集合,scala,collections,Scala,Collections,我编写了以下代码: class MyActor extends Actor { override def receive: Receive = { case p: Set[String] => // } } 但编译时会发出以下警告: Warning:(22, 13) non-variable type argument String in type pattern scala.collection.immutable.Set[String] (the underlyin

我编写了以下代码:

class MyActor extends Actor {
  override def receive: Receive = {
    case p: Set[String] => //
  }
}
但编译时会发出以下警告:

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] =>

为什么??除了suppressing之外,还有什么方法可以消除它吗?

您不能在任何类型参数上真正进行模式匹配,这是设计上的,因为JVM运行时在运行时没有类型参数的概念

最简单的方法是将其包装在一个值类中

case class StringSet(val value: Set[String]) extends AnyVal
然后,您可以轻松地在其上进行模式匹配:

override def receive: Receive = {
  case StringSet(p) => //
}

不完全重复,但非常接近:@Vidya足够接近…请参见类型擦除。这里有实际错误。首先,当您进行模式匹配时,值类实际上会在运行时实例化。其次,
StringSet
需要是一个case类,或者如果您想对其进行模式匹配,则需要在
StringSet
的伴生对象中定义一个
。但从好的方面来看,您将类型擦除视为问题所在,并正确地指出,在构造函数上而不是类型上进行模式匹配才是解决方法。