On 23.07.2017 00:28, Daniel Sun wrote:
Hi all,
I've been thinking about Union Type for method/constructor
declaration. It is similar to multi-catch in try-catch statement, e.g.
class UnionTypeSample {
public UnionTypeSample(A|B|C p) {
// do something
}
def m(D|E p) {
// do something
}
}
Groovy will translate the above code into the following code, which is
also the same way how multi-catch is handled.
class UnionTypeSample {
public UnionTypeSample(A p) {
// do something
}
public UnionTypeSample(B p) {
// do something
}
public UnionTypeSample(C p) {
// do something
}
def m(D p) {
// do something
}
def m(E p) {
// do something
}
}
Any thoughts?
writing while thinking about it... how about static compilation and
related: AST modeling? I assume you intend to do this transformation at
a pretty early stage, copying the AST nodes into other methods. But I
really would not call this union types, maybe union overloads or such.
Union types would go much much further.
For example in
def y
if (x) {
y = 1
} else {
y = "1"
}
y should then have the type (Integer|String) in static compilation,
while right now this is going to be a union of all the common classes of
Integer and String. Which means an intersection, just not limited to a
single type. And I think at this point simple AST copying will no longer
do the job. This would mandate a new AST element. And I think for a
clean solution we should then actually rewrite ClassNode. Syntax wise I
I think we can solve a problem like this:
def A,B
def y = {A|B param -> A|B}
I do not see a blocker here right now. But of course the alternative is
to declare the type and bypass the representation problem in a ClassNode
as well as possible syntax problems:
class union MyUnionTypeABC = A|B|C
class union MyUnionTypeDE = D|E
class UnionTypeSample {
public UnionTypeSample(MyUnionTypeABC p) {
// do something
}
def m(MyUnionTypeDE p) {
// do something
}
}
of course we still need a syntax for the definition after all... I guess
nothing is really easy in the end.
And if we are never going to do full union types, is it then worth
having the overload union only?
I think code coverage tools will have a problem with this, but maybe
they would regardless what implementation we would choose.
bye Jochen