var, static factory method and value type constructor
Remi Forax
forax at univ-mlv.fr
Sat Oct 6 09:55:01 UTC 2018
I've observed an interesting side effect of the introduction of var that troubles my students,
the introduction of var make the generics method call with type arguments needed to be mentioned more frequent.
writing
List<String> list = List.of();
foo(list); // foo takes a List of String
works out of the box but
var list = List.of();
foo(list);
will not compile because list is inferred as List<Object>
Explicitly specifying the type arguments
var list = List.<String>of();
foo(list);
works but this syntax is far from obvious for my students.
This lead me to think again about introducing a syntax for supporting static factory method (yes, i know, it seems remote, but it's connected).
My students has no issue with specifying the type argument when calling a constructor
var list = new ArrayList<String>();
so
why not resurrect the proposal to have a syntax to be able to declare static factory method at language level and being able to call it with new ?
I propose to re-use 'new' when defining a static factory method
interface Fun {
static Fun new() {
return ...
}
}
and teach the compiler that new Fun() should be translated to invokestatic Fun.new() in this case.
It is obvioulsly related to value types and the way the compiler currently desugars constructor of value type. The desugaring of the constructor call is exactly the same as this proposal,
what we are adding here is the fact that a developer can ask for such translation by adding a static factory instead of being only a magic translation from the compiler.
Rémi
More information about the valhalla-spec-observers
mailing list