使用ScalaPB创建具有泛型类型的函数

时间:2018-06-03 08:30:24

标签: scala generics scalapb

我有以下功能(适用于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 = {

但仍会出现更多错误

我做错了什么?

1 个答案:

答案 0 :(得分:0)

JsonFormat.fromJsonString需要隐式GeneratedMessageCompanion。如果您将签名更改为:

,它将起作用
def createResponseFromJson[A <: scalapb.GeneratedMessage with scalapb.Message[A]
     : GeneratedMessageCompanion](protoJsonFile: String): A