Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <h2>This answer uses the <code>Manifest</code>-API, which is deprecated as of Scala 2.10. Please see answers below for more current solutions.</h2> </blockquote> <p>Scala was defined with Type Erasure because the Java Virtual Machine (JVM), unlike Java, did not get generics. This means that, at run time, only the class exists, not its type parameters. In the example, JVM knows it is handling a <code>scala.collection.immutable.List</code>, but not that this list is parameterized with <code>Int</code>.</p> <p>Fortunately, there's a feature in Scala that lets you get around that. It’s the <strong>Manifest</strong>. A Manifest is class whose instances are objects representing types. Since these instances are objects, you can pass them around, store them, and generally call methods on them. With the support of implicit parameters, it becomes a very powerful tool. Take the following example, for instance:</p> <pre><code>object Registry { import scala.reflect.Manifest private var map= Map.empty[Any,(Manifest[_], Any)] def register[T](name: Any, item: T)(implicit m: Manifest[T]) { map = map.updated(name, m -&gt; item) } def get[T](key:Any)(implicit m : Manifest[T]): Option[T] = { map get key flatMap { case (om, s) =&gt; if (om &lt;:&lt; m) Some(s.asInstanceOf[T]) else None } } } scala&gt; Registry.register("a", List(1,2,3)) scala&gt; Registry.get[List[Int]]("a") res6: Option[List[Int]] = Some(List(1, 2, 3)) scala&gt; Registry.get[List[String]]("a") res7: Option[List[String]] = None </code></pre> <p>When storing an element, we store a "Manifest" of it too. A Manifest is a class whose instances represent Scala types. These objects have more information than JVM does, which enable us to test for the full, parameterized type.</p> <p>Note, however, that a <code>Manifest</code> is still an evolving feature. As an example of its limitations, it presently doesn't know anything about variance, and assumes everything is co-variant. I expect it will get more stable and solid once the Scala reflection library, presently under development, gets finished.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload