3

I want to the get the manifest of one List's inner type like following and pass it to another function, how can I do that ? Thanks

  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]) = {}
zjffdu
  • 25,496
  • 45
  • 109
  • 159

2 Answers2

5

Add the manifest as an implicit requirement to your method, and tweak the type signature a tiny bit:

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...
}

The Manifest class has a method, typeArguments, that should serve your purpose for finding the "inner type". For example

manifest[List[Int]].typeArguments == List(manifest[Int])
Dylan
  • 13,645
  • 3
  • 40
  • 67
2

You could tweak @Dylan's answer a bit and try this as well:

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))
  }
}
cmbaxter
  • 35,283
  • 4
  • 86
  • 95