Is there a way to extract an item type from the manifest [List [X]] in Scala?

I know that something is List [_] based on the manifest I passed to the method, but I need to know which list item. Is this information stored in a manifest somewhere and can you solve it? If not, any suggestions on how to work around the problem?

(Basically, I have Map [Manifest [_], Blah], where Blah handles cases based on the class type. List processing [X] is compound based on X, but I need to find out that X is what I can extract its Blah value from the map.)

Thanks!

+4
source share
3 answers

I think you are looking for typeArguments

scala> manifest[List[Int]] res1: Manifest[List[Int]] = scala.collection.immutable.List[Int] scala> res1.typeArguments res2: List[scala.reflect.Manifest[_]] = List(Int) scala> res2.head res3: scala.reflect.Manifest[_] = Int scala> res3.erasure res4: java.lang.Class[_] = int 
+6
source

It's hard to tell you what to do without a piece of example code. Therefore, from what you wrote, I assume that you get the parameter A [B]. This should work as follows:

 def foo[A[B], B](x: A[B])(implicit outer: ClassManifest[A[B]], inner: ClassManifest[B]) = { // your code here } 
+5
source

So, you have Manifest[List[T]] and you want to process based on T ? What about

 def listType[T](m: Manifest[T]) = if (m.erasure == classOf[List[_]]) m.typeArguments match { case List(c) if c.erasure == classOf[Int] => "it a List[Int]" case List(c) if c.erasure == classOf[String] => "it a List[String]" case _ => "some other List" } else "not a List" scala> listType(implicitly[Manifest[List[Int]]]) res29: java.lang.String = it a List[Int] 
+1
source

Source: https://habr.com/ru/post/1400993/


All Articles