如何在模式匹配中获得清单

时间:2013-04-29 11:20:03

标签: scala manifest

我想得到一个List的内部类型的清单,如下所示并将其传递给另一个函数,我该怎么做?谢谢

  def f(any: Any) = any match {
    case x: Int => println("Int")
    case a: List[_] => // get the manifest of List's inner type, and use it in the function g()
  }

  def g[T:Manifest](list:List[T]) = {}

2 个答案:

答案 0 :(得分:5)

将清单添加为方法的隐式要求,并稍微调整类型签名:

def f[T](any: T)(implicit mf: Manifest[T]) = mf match {
  case m if m == Manifest[Int] => println("Int")
  case m if m == Manifest[List[Int]] => println("List of Ints")
  //etc...
}

Manifest类有一个方法typeArguments,它应该用于查找“内部类型”的目的。例如

manifest[List[Int]].typeArguments == List(manifest[Int])

答案 1 :(得分:2)

你可以稍微调整一下@Dylan的答案并试试这个:

object ManifestTest {
  def f[T](t: T)(implicit m:Manifest[T]) = t match {
    case x: Int => println("Int")
    case a: List[Any] => 
      val innerType = m.typeArguments.head
      println(innerType)
  }

  def main(args: Array[String]) {
    f(1)
    f(List("hello", "world"))
    f(List(1))
  }
}