ScalaBuff icon indicating copy to clipboard operation
ScalaBuff copied to clipboard

Alternative to reflection for union types

Open mmaz opened this issue 10 years ago • 2 comments

Is there an idiomatic way in ScalaBuff for deserializing a union-type container? This would obviate the need for protocol buffer reflection via getAllFields with Java-generated classes. For example, using OneMessage from the protocol buffer documentation :

//not using ScalaBuff
OneMessage.parseFrom(msg).getAllFields.values.asScala.foreach { m =>
  //do something with Foo, Bar, or Baz, e.g. post to Guava EventBus
  bus.post(m)  //m is an AnyRef but EventBus dispatches to correct subscriber
}

mmaz avatar Aug 20 '13 13:08 mmaz

My current workaround is to explicitly match on each type. Using the above as an example again:

val bus = new EventBus()
val om = OneMessage.parseFrom(bytes)
List(om.foo, om.bar, om.baz).flatten.map(bus.post)

This works, but it is a bit more laborious when the protobuf definition changes

mmaz avatar Aug 20 '13 14:08 mmaz

You can propose a solution that doesn't impact the generated code size too much and if it sounds good, I'll implement it.

I'm not sure but I think you can maybe use the Shapeless library to treat case classes as functional constructs. Maybe some sort of direct support for Shapeless could be added as well.

SandroGrzicic avatar Aug 20 '13 14:08 SandroGrzicic