Alec Muffett
12/02/2020, 10:06 AMProtobuf
and Square's Wire
to serialise data, and to deserialise into Kotlin.
Just like the example at https://github.com/square/wire#protocol-buffers I have a common Dinosaur
message which has got a name
string
The first and obvious change in the direction that I want to go, would be to replace the name
with a protobuf enum
so that I get Dinosaur.STEGOSAURUS
(etc) as a nameEnum, which means that the code can find out the soft-type of the message; but that doesn't give me what I want.
The second approach would be to use the protobuf oneof
type - and it would essentially do exactly the same soft-type thing - I could use Dinosaur.STEGOSAURUS.foo.bar
- but that still does not give me what I want.
What I want is for the deserialisation process of a Dinosaur
message to yield a Stegosaurus
type; or a TRex
or Apatosaurus
type, or whatever, so that resulting code can guarantee having an Apatosaurus
passed into it. I am presuming that some sort of DinosaurParser.peekType()
and DinosaurParser.getApatosaurusOrThrow()
will be needed, along with a type-enforcement is/as
check.
But that leaves me with the question of delegation so that I can access the other fields of the Dinosaur
message, like height, weight, etc.
• what's the best way for me to convert a "Dinosaur-message-with-TRex-soft-type" in the serialisation domain
• into a kotlin-domain strongly-typed-instance-of-TRex
that the compiler can check
• but also inherit (delegate?) all the accessors and methods from the underlying Dinosaur
message, into the TRex
instance?
It would be nice to do:
class TRex(d: Dinosaur) : Dinosaur by d
...however the protobuf compilers are generating Dinosaur
classes, not interfaces, so I don't think that option is open to me?Alec Muffett
12/02/2020, 10:51 AMDinosaur
messages, etc, will be common across all of TRex
, Stegosaurus
, Apatosaurus
, etc; so it would be redundant and wasteful to have separate Protobuf "messages" for each, plus it would cause proliferation of other handler code that could simply be written in terms of Dinosaur
. The goal here is to use Kotlin type-safety for methods which demand one-or-other kinds of Dinosaur.Alec Muffett
12/02/2020, 10:53 AMAlec Muffett
12/03/2020, 6:58 AM