3

我想像下面这样获取一个列表的内部类型的清单并将其传递给另一个函数,我该怎么做?谢谢

  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]) = {}
4

2 回答 2

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])
于 2013-04-29T11:47:32.893 回答
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))
  }
}
于 2013-04-29T11:58:28.443 回答