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

zjf*_*fdu 3 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]) = {}
Run Code Online (Sandbox Code Playgroud)

Dyl*_*lan 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...
}
Run Code Online (Sandbox Code Playgroud)

该Manifest班有一个方法,typeArguments即应该成为你的寻找"内部型"的宗旨.例如

manifest[List[Int]].typeArguments == List(manifest[Int])
Run Code Online (Sandbox Code Playgroud)