Union type code generation for OO languages?


I am wondering if there exist examples or guidelines on how generated code should look like when working with union types. I am thinking particularly about Java, Scala, Python, C# and Swift as target languages.

It is manageable to handle multiple inheritance, but RAML 1.0 is very generous with mixing types in union types, multiple inheritance and both together. So… has anyone thought about how this should look like in strongly typed languages?

Is support for type classes (or generics, e.g. Tree<T> where type T can be defined later) on the roadmap?



Hi Peter,

I am handling union types in https://github.com/OnPositive/aml/tree/master/org.aml.raml2java. (any comments issues are very appreciating). General approach that I have in mind is the following:

  • Build types for all union types options (this may be required if you are extending from union type and adding properties)
  • Model union type as a type with a set of fields representing possible options.
  • Generate code which discriminates data against union type options and determines actual type of the instance. It may be done using discriminator or by building AC (automatic classification algorithm).

Regards, Pavel


I see that you already modeled a typesystem for RAML 1.0. I’ll definitely have a look at it since I’m currently seriously refactoring the typesystem that I was using for 0.8 in order to support 1.0.

Your approach for union types makes sense. I had thought about providing some ‘public R process(…)’ method in the union type that takes n Function<Tx,R> objects, where x=1…n and n is the number of types the union type holds and Tx the types. Only one of the functions is applied, namely the one that matches the actual type Ty that is held inside the union type. The result ‘R’ is then the result of whatever you want to do with the union object. You could compare it to pattern matching in Scala, or maybe see it as some sort of visitor.

Thanks for the input.


Only one of the functions is applied, namely the one that matches the actual type Ty that is held inside the union type

Yep, this is exactly the thing that I am naming AC (automatic classification), for now I am limiting it to required property sets and type kinds, to simplify code generation but potentially you can go indefinitely deep in the algorithm if you want.

BTW: just looked in http://scraml.io/javadocumentation/#raml-generic-typing and it is pretty nice.


BTW: I have looked in your Scraml parser and as well as I see you are basing on JSON output there.

In fact I think you can benefit from using https://github.com/OnPositive/aml/tree/master/org.aml.model/src/main/java/org/aml/apimodel which is a common model on top of RAML 0.8 and RAML 1.0. It is far from perfect yet and suffers from a bugs in RAML java parser, but working good enough to let me implement initial version of RAML 1.0 support for RAML for JAXRS( https://github.com/mulesoft/raml-for-jax-rs/pull/200 )