scala pass T type to Java constructor

Viewed 72

I am using Jackson read Yaml in scala 2.11/2.12 val mapper = new ObjectMapper(new YAMLFactory()), I think the Java constructor I am calling is

public <T> T readValue(String content, Class<T> valueType)

this code works

def load(): SomeClass {
  mapper.readValue[SomeClass](configStr, classOf[SomeClass])
}

But I want to change this class to T

mapper.readValue[T](configStr, classOf[T])

error class type required but T found

I searched some and changed it to

def load[T: ClassTag](): T = {
  mapper.readValue[T](configStr, classTag[T].runtimeClass)
}

But it says no construct methods are matched.

1 Answers

The return type of classTag[T].runtimeClass is a Class[?], you have to use .asInstanceOf (safe in this usage):

mapper.readValue[T](configStr, classTag[T].runtimeClass.asInstanceOf[Class[T]])

Note that if you were using the Jackson Scala module, such methods are already provided to you in order to avoid the boilerplate

Related