问题描述
我有一些对json对象执行一些常见操作的代码,即提取。所以我想创建一个泛型函数,该类型参数需要类型,代码如下所示:
def getMessageType [T](json:JValue):要么[GenericError,T] = {
尝试{
正确(json.extract [T])
} catch {
case e: MappingException => jsonToError(json)
}
}
问题是如何通过T信息到那个功能?
如果您看:您将看到它需要
Manifest
隐式:
def extract [A](json: JValue)
(隐式格式:格式,mf:Manifest [A]):A
这通过将类型作为值来解决JVM类型的擦除。对于您的
的情况,我认为您应该做同样的事情:
def getMessageType [T](json:JValue )
(隐式f:格式,mf:Manifest [T]):T =
{
json.extract [T]
}
这:
隐式参数,必须由调用者完成。
- code>。
创建(相同的)隐式参数以将它们传递给
extract
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: JValue): 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 yourcase, I think you should do the same thing:
def getMessageType[T](json: JValue) (implicit f: Formats, mf: Manifest[T]): T = { json.extract[T] }
This:
Gives your method implicit parameters, which must be fulfilled by the caller.
Creates (those same) implicit parameters to pass them on to
extract
.
这篇关于传递类型信息以在Scala中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!