Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get manifest in the pattern matching

Tags:

manifest

scala

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]) = {}
like image 612
zjffdu Avatar asked May 14 '26 02:05

zjffdu


1 Answers

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])
like image 146
Dylan Avatar answered May 15 '26 18:05

Dylan