mercredi 30 septembre 2015

How to cast Any to Array[T] maintaining Scala's invariance for arrays

I tried to implement the following function maintaining Scala's invariant view over the JVM arrays:

def cast[T](a: Any): Option[Array[T]] = ???

That is, given:

class Foo
class Bar extends Foo

the following examples should work and return Some:

val arr1: Any = Array(new Bar)
cast[Bar](arr1) // OK

val arr2: Any = Array(1, 2, 3)
cast[Int](arr2) // OK

val arr3: Any = Array("a", "b", "c")
cast[String](arr3) // OK

The following one, instead, should return None:

val arr: Any = Array(new Bar)
cast[Foo](arr1) // KO, violates invariance

I tried through reflection using ClassTag/TypeTag with no luck, but since I'm no reflection expert I could be missing something.





Aucun commentaire:

Enregistrer un commentaire