How to get a classOf[Array[T]] in Scala

Viewed 55

I have a method (scala 2.12) that does look like the following.

The goal is to pass to the method readValue from objectMapper (jackson) a string and a class that the string needs to be casted, which in this case is an Array[T].

T can be two different case classes and therefore that is the reason of why I try to parametrize it.

private def fromSeqToCastedSeq[T](files: Seq[File]): Seq[T] = {
files flatMap (file => {
  val maps = objectMapper.readValue(file, classOf[Map[String, Any]])
  val combinedString = objectMapper.writeValueAsString(maps.get("sqlDefinitions"))
  val o = objectMapper.readValue(combinedString, classOf[Array[T]])
  o})

Currently this does not compile with a scala.MatchError because it is not able to cast it at runtime.

Could someone help me understand if what I'm trying to achieve is possible?

Thanks.

1 Answers

As answered in Discord, you should be able to do this:

import scala.reflect.ClassTag

private def fromSeqToCastedSeq[T](files: Seq[File])(implicit ct: ClassTag[T]): Seq[T] = {
  val arrayTClass = ct.wrap.runtimeClass.asInstanceOf[Class[Array[T]]]

  files.flatMap { file =>
    val maps = objectMapper.readValue(file, classOf[Map[String, Any]])
    val combinedString = objectMapper.writeValueAsString(maps.get("sqlDefinitions"))
    objectMapper.readValue(combinedString, arrayTClass)
  }
}

Now, no idea if this will crash at runtime, is highly probably given this piece of code is extremely unsafe and unidiomatic.

Related