Is it possible to have a manifest defined based on another manifest in Scala?
I've pretty much resigned myself to the belief that this is not possible because the Scala Manifest information was not intended to be used dynamically.
Here's the problem. I have a function that can return more than one type of object (String, Int, List[Int], List[List[String]], etc.) To support these multiple types, the return type is set to Any, but due to type erasure the information about the types supported in Lists, Maps, etc is lost. In an attempt to recover some of the details, I return a Manifest along with the return type.
However, the returned information may then be placed in another list or map and that is then returned from another function. I want to update the manifest to include the fact that the type is now a List or Map of the previous type as defined by the manifest.
Here's some example code
def returnWithManifest[T: Manifest](x: T) = (x, manifest[T])
// May return String, Int, List[Int], List[List[String]], ...
def contrivedExample(t: String): (Any, Manifest[_]) = t match {
case "String" => returnWithManifest("test")
case "Int" => returnWithManifest(1)
case "Boolean" => returnWithManifest(true)
case "List[Int]" => returnWithManifest(List(1,2,3))
case "List[List[String]]" =>
returnWithManifest(List(List("a","b"),List("c","d")))
case _ => returnWithManifest(None)
}
scala> val v1 = contrivedExample("List[Int]")
v1: (Any, Manifest[_]) = (List(1, 2, 3),scala.collection.immutable.List[Int])
scala> val x = v1._1
x: Any = List(1, 2, 3)
scala> val m = v1._2
m: scala.reflect.Manifest[_] = scala.collection.immutable.List[Int]
scala> val v2 = List(x)
v2: List[Any] = List(List(1, 2, 3))
From the manifest of 'v1' I know that v1 is of type List[Int] so when I create 'v2' I should have all the information I need to create a manifest identifying that the type is List[List[Int]], but instead I only have List[Any] to work with. Perhaps syntax like the following:
val v2: m = List(x)
val v2 = List[m](x)
I realize it looks like I'm trying to define a type dynamically, but in reality the information is metadata related to type erasure of statically known types. I guess if this can be solved, then type erasure can be solved. However, at the very least I thought I should be able to do something like:
scala> val m2 = m.wrapInList()
m2: scala.reflect.Manifest[_] =
scala.collection.immutable.List[scala.collection.immutable.List[Int]]