SandroGrzicic / ScalaBuff

the scala protocol buffers (protobuf) compiler
Other
219 stars 80 forks source link

Alternative to reflection for union types #68

Open mmaz opened 11 years ago

mmaz commented 11 years ago

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 commented 11 years ago

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

SandroGrzicic commented 11 years ago

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.