首页 文章

Scala模式匹配类型参数

提问于
浏览
1

我想摆脱这个示例代码的类型擦除警告:

val a: Seq[Any] = Seq(1)
a match {
  case b: Seq[Int] => b.map(c => println(2 * c) )
  case _ => println("Not matched")
}

它编译并正常工作,但有一个警告:

警告:(31,13)类型模式中的非变量类型参数Int Seq [Int](Seq [Int]的基础)未被选中,因为它被擦除情况b消除:Seq [Int] => b.map (c => println(2 * c))^

在这种情况下,您是否有任何简单的解决方案来避免擦除?

到目前为止我尝试了什么(符合this):

val a: Seq[Any] = Seq(1)
a match {
  case b@Seq(_:Int) => b.map(c => println(2 * c) )
  case _ => println("Not matched")
}

但它不会编译,因为c现在是Any类型 .

我相信这个问题有几个解决方案 . 我会接受最简单的一个 .

3 回答

  • 0

    这个

    case b: Seq[Int @unchecked] => b.map(c => println(2 * c))
    

    将摆脱警告 . 但它不能解决基本的擦除问题 . Seq("1") 将匹配此案例 .

  • 0

    我有同样的问题,我最终做了这样的事情(没有找到更漂亮的东西):

    val a: Seq[Any] = Seq(1)
    a match {
      case b: Seq[_] => b.map(c =>
        c match {
          case s: Int => print(2 * s)
          case _ => print("Not matched")
        })
      case _ => print("Not matched")
    }
    
  • 0

    我'm not sure the this is a simplest solution but I think it'更好地匹配 TypeTag 的类型

    def matchOnList[A: TypeTag](l: List[A]) = typeOf[A] match {
        case t if t =:= typeOf[Int] =>
          l.asInstanceOf[List[Int]].foreach(c => println(2 * c))
        case _ => println("Not matched")
      }
    
    val a = List(1)
    
    matchOnList(a)
    

相关问题