我有以下功能(适用于protobuf对象MyRequest
def createRequestFromJson(requestJson: String): MyRequest = {
val protoJson = getResource(requestJson)
JsonFormat.fromJsonString[MyRequest](protoJson)
}
我想将这个函数重用于另一个对象,所以我添加了一个类型
def createRequestFromJson[A](requestJson: String): A = {
val protoJson = getResource(requestJson)
JsonFormat.fromJsonString[A](protoJson)
}
然后我收到错误
Error:(68, 30) type arguments [A] do not conform to method fromJsonString's type parameter bounds [A <: scalapb.GeneratedMessage with scalapb.Message[A]]
JsonFormat.fromJsonString[A](protoJson)
我尝试将定义更改为
def createResponseFromJson[A <: scalapb.GeneratedMessage with scalapb.Message[A]](protoJsonFile: String): A = {
但仍会出现更多错误
我做错了什么?
答案 0 :(得分:0)
JsonFormat.fromJsonString
需要隐式GeneratedMessageCompanion
。如果您将签名更改为:
def createResponseFromJson[A <: scalapb.GeneratedMessage with scalapb.Message[A]
: GeneratedMessageCompanion](protoJsonFile: String): A