使用ScalaPB创建泛型类型的函数
我有以下函数(在protobuf对象MyRequest上工作使用ScalaPB创建泛型类型的函数,scala,generics,scalapb,Scala,Generics,Scalapb,我有以下函数(在protobuf对象MyRequest上工作 def createRequestFromJson(requestJson: String): MyRequest = { val protoJson = getResource(requestJson) JsonFormat.fromJsonString[MyRequest](protoJson) } 我想用不同的对象重用这个函数,所以我添加了一个类型 def createRequestFromJson
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)
错误:(68,30)类型参数[A]不符合JsonString的类型参数边界[AJsonFormat]的方法。fromJsonString
需要一个隐式的GeneratedMessageCompanion
。如果将签名更改为:
def createResponseFromJson[A <: scalapb.GeneratedMessage with scalapb.Message[A]
: GeneratedMessageCompanion](protoJsonFile: String): A
def createResponseFromJson[A]
def createResponseFromJson[A <: scalapb.GeneratedMessage with scalapb.Message[A]
: GeneratedMessageCompanion](protoJsonFile: String): A