【发布时间】:2015-08-04 20:32:00
【问题描述】:
我有 3 个函数,kk expect Array[Byte] 或 List[Array[Byte]],所以我做了一个模式匹配,
def gg (a :Array[Byte]) = "w"
def ff (a :List[Array[Byte]]) = "f"
def kk(datum : Any) = datum match {
case w : Array[Byte] => gg(w)
case f :List[Array[Byte]] => ff(f)
case _ => throw new Exception("bad data")
}
当我尝试编译代码时出现错误:
类型模式 List[List[Any]](List[List[Any]] 的底层)中的非变量类型参数 List[Any] 未被选中,因为它被擦除消除了
所以我将 kk 函数构造为流动的,现在可以编译它:
def kk(datum : Any) = datum match {
case w : Array[Byte] => gg(w)
case f :List[_] => ff(f.asInstanceOf[List[Array[Byte]]])
case _ => throw new Exception("bad data")}
我的问题:
1:我当前的kk 版本是为List 进行模式匹配的惯用方式吗?如果没有,有人可以告诉我怎么做吗?
2:如果我想对List[Any] 和List[List[Any]] 进行模式匹配,我该怎么做?如果我的数据类型为List[Byte],(ff(f.asInstanceOf[List[Array[Byte]]]) 可能会导致错误)
【问题讨论】:
-
感谢您的帖子,我认为stackoverflow.com/questions/12218641/… 也是一个好地方。
-
阅读后,新代码应如下所示: def gg (a :Array[Byte]) = "w" def ff (a :List[Array[Byte]]) = "f" def binaryDecodexx[A : TypeTag](datum : A) = typeOf[A] match { case t if t =:= typeOf[Array[Byte]] => gg(datum.asInstanceOf[Array[Byte]]) case t if t =:= typeOf[List[Array[Byte]]] => ff(datum.asInstanceOf[List[Array[Byte]]]) // case w : Array[Byte] => gg(w) // case f :列表[_] => }
标签: scala