zjffdu
zjffdu

Reputation: 28814

How to get manifest in the pattern matching

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

Upvotes: 3

Views: 1106

Answers (2)

cmbaxter
cmbaxter

Reputation: 35453

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

Upvotes: 2

Dylan
Dylan

Reputation: 13922

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])

Upvotes: 5

Related Questions