开发者

Passing type information to function in Scala

开发者 https://www.devze.com 2023-04-10 11:22 出处:网络
I have code that does some common operation on json objects, namely extract. So what I would like to create generic function that takes type parameter which class to expect, code looks like as follows

I have code that does some common operation on json objects, namely extract. So what I would like to create generic function that takes type parameter which class to expect, code looks like as follows:

def getMessageType[T](json: J开发者_如何学GoValue): Either[GenericError,T] = {
  try {
    Right(json.extract[T])
  } catch {
    case e: MappingException => jsonToError(json)
  }
}

The issue is how to pass T information to that function ?


If you look at the definition of extract: you will see that it takes a Manifest implicitly:

def extract[A](json: JValue)
    (implicit formats: Formats, mf: Manifest[A]): A

This gets around JVM type erasure by taking the "type" in as a value. For your case, I think you should do the same thing:

def getMessageType[T](json: JValue)
    (implicit f: Formats, mf: Manifest[T]): T =
{
    json.extract[T]
}

This:

  1. Gives your method implicit parameters, which must be fulfilled by the caller.

  2. Creates (those same) implicit parameters to pass them on to extract.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号