Search code examples
jsonscalatype-erasure

How to get type declared from Iterable in Scala?


I am wondering if there is way to get the declared type in the underlying Iterable as in:

var string: Seq[String] => I want something to return String 
var int: Seq[Int] = _ => I want something to return Int
var genericType: Seq[A] => I want to return A

I need to know the class of these types so I can use the underlying Json Library to deserialize the json string into this type.

Something like

def fromJson[A](jsonString: String)(implicit tag: TypeTag[A]): A =  ???

Thanks


Solution

  • I might have not provided enough information in my question. Anyway, I found out the answer.

    In order to retrieve a class from a generic type I had to do the following

    import scala.reflect.runtime.universe._
    val m = runtimeMirror(getClass.getClassLoader)
    def myMethod[A](implicit t: TypeTag[A]) = {
      val aType = typeOf[A]
      aType.typeArgs match {
         case x: List[_] if x.nonEmpty => m.runtimeClass(x.head)
         case x: List[_] if x.isEmpty => m.runtimeClass(aType)
      }
    }
    scala> myMethod[Seq[String]]
    res3: Class[_] = class java.lang.String
    
    scala> myMethod[Seq[Int]]
    res4: Class[_] = int
    
    scala> case class Person(name: String)
    defined class Person
    
    scala> myMethod[Seq[Person]]
    res5: Class[_] = class Person
    
    scala> myMethod[Person]
    res6: Class[_] = class Person
    

    I can then provide this class to the underlying library to do its job. Thanks