mukh007
mukh007

Reputation: 339

Scala passing class type as an argument

Hey I'm trying to write below code in best possible way in scala, please help me if there is a better way!

public final <T> T deserialize(String jsonString, Class<T> klass) {
    try {
        return objectMapper.readValue(jsonString, klass);
    } catch (Exception e) {
        LOG.error("Failed to deserialize {} to class {}, {}", jsonString, klass, e);
    }
    return null;
}

Is below a good one?

  def deserialize[T: Manifest](value: String): T = {
    mapper.readValue(value, typeReference[T])
  }

Upvotes: 1

Views: 4964

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

If you need to obtain a Class[T], use scala.reflect.ClassTag (not TypeTag; you can get the Class from it, but only in a round-about way):

def deserialize[T](value: String)(implicit tag: ClassTag[T]): T = {
  mapper.readValue(value, tag.runtimeClass.asInstanceOf[Class[T]])
}

Be careful not to forget the type parameter when calling (i.e. deserialize[String]("\"a\""), not deserialize("\"a\"")), or Scala will infer it to be Nothing.

It's also possible you'll need to pass boxed classes instead of primitives (e.g. deserialize[java.lang.Integer]("1")), if so you can fix the problem but this will require extra code.

Upvotes: 5

Related Questions