WestCoastProjects
WestCoastProjects

Reputation: 63082

How to obtain a scala.reflect.Manifest from a type parameter

We have an existing API that require a scala.reflect.Manifest . The api requires invocation like this:

 def extractConfig[C: Manifest](config: JObject) : C

. What we have to work with is:

abstract class MyApp[T <: MyType[T], U <: MyOtherType] extends App

Is there a way to obtain a scala.reflect.Manifest for U just given the definition shown above ? Something like this:

 abstract class MyApp[T <: MyType[T], U <: MyOtherType : Manifest] extends App {
 ..
 val jsonObj: JObject = getJson()
 val cfg: U = extractConfig[U](jsonObj)  // "No manifest found for Type U"

However the U <: MyOtherType : Manifest does not work: it does compile. But at runtime we have

No manifest found for type U

on the noted line.

Is there some detail that may be added to the type declarations to get the Manifest set up properly?

** Update ** The core issue is the Json4s api that requires a Manifest. It is not clear why that were the case: i.e. why is Json4s unable to determine the Manifest itself for any type parameter.

Invocation code:

 val cfg = parse(readResource(path)).extract[C]

Json4s source code:
https://github.com/json4s/json4s/blob/3.6/core/src/main/scala/org/json4s/ExtractableJsonAstNode.scala#L20-#L21

def extract[A](implicit formats: Formats, mf: scala.reflect.Manifest[A]): A =
  Extraction.extract(jv)(formats, mf)

Upvotes: 2

Views: 1596

Answers (1)

Assaf Mendelson
Assaf Mendelson

Reputation: 13001

Not sure why you got the error message as this is the correct way of doing so (maybe you could post the code for U), however, doing : manifest is just a syntactic sugar for (implicit ev: manifest[U]) so you could do:

abstract class MyApp[T <: MyType[T], U <: MyOtherType](implicit ev: manifest[U]) extends App

BTW, in scala 2.11 and on, the suggested replacement for manifest are TypeTags and ClassTag (see http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html)

Upvotes: 1

Related Questions