Description
I've been looking at the generated code for Android, and I think we could really make it a lot more natural by generating constructors for Java classes instead of relying on creator methods.
The idea behind my proposal is that we could simply detect specific function naming convention in Go, and if that holds, generate a constructor instead of a static method.
Basic constructors
If I were to have a type on Go side:
type SomeType struct {}
Then either of the functions below could be interpreted as a constructor for SomeType
:
func NewSomeType(arg string) *SomeType {...}
func NewSomeType(arg string) (*SomeType, error) {...}
Instead of generating a static method in the root namespace, we could generate a public constructor:
class SomeType {
public SomeType(String arg) { ... }
}
The rule would be that if a Go package contains both TypeXXX and a function NewTypeXXX which returns TypeXXX and optionally an error, we can interpret that as a constructor.
Overloaded constructors
An even more interesting (alas less obvious) case are overloaded constructors. Many times it can happen that we need to create a new "object" from multiple possibly input types.
One example of such is Go's binary
package:
func NewBuffer(buf []byte) *Buffer { ... }
func NewBufferString(s string) *Buffer { ... }
In this case the "Basic" approach above would generate a constructor from the first, but not the second function. I'd propose that all functions called NewTypeXXX<whatever>
that have the required signature (returns a pointer to a type and an optional error) is used to generate overloaded constructors.
Clashes
Of course, since we're "merging" different named methods under the same constructor name, there's nothing stopping me from defining multiple methods in Go that would en up with the same constructor signature.
func NewBuffer1(buf []byte) *Buffer { ... }
func NewBuffer2(buf []byte) *Buffer { ... }
In that case we can just fall back to the current behavior of retaining the methods and not creating constructors out of them.
I'd be happy to code this up if there's interest. @eliasnaur ? :)