Aliases to solve unboxed value types naming?
Piotr Tarsa
piotr.tarsa at gmail.com
Sat Jul 2 16:06:20 UTC 2022
Hi,
Maybe introducing type aliases to Java would remove the need for
explicit naming of the unboxed value types companions?
Type aliases can be powerful (like in Scala, where they can be
imported, exported, inherited, generic, can be members like fields and
values, can be implemented by classes, etc) or restricted (like in C#,
where aliases are file level only, can't have generic parameters
themselves, can't be members of objects, etc). Even the restricted
ones could solve the problem of unwanted suffixes, e.g.
// ComplexBox.java - value type definition
package com.plex;
public value class ComplexBox {
public value companion;
}
// App.java - value type usage
package com.pany.app;
alias Complex = comp.plex.ComplexBox.val;
public class App {
... main(... args) {
val complex = new Complex(1.5, -3.8); // no .val suffix needed
System.out.println(complex);
}
}
Type aliases can solve a range of problems, not only naming of unboxed
value types. Type aliases can also help when:
- we have conflicting imports (i.e. we want to use two classes with
same names, but different packages) and want to avoid repeating fully
qualified name of one or more of them. This could happen e.g. when
migrating from one utility library to one, e.g. from joda-time to
java.time. I think such scenarios aren't very rare, but are
particularly annoying (the fully qualified name looks very ugly in the
middle of source code).
- there are some classes with super long names, e.g.
AbstractSingletonPancakeProxyFactoryBean, which we locally (on
file-level) use many times (e.g. construct in a few methods), but
don't want to spell out such long names every time and locally we
won't have problems with ambiguity when using short alias. Such
scenario is probably very rare (unless we're using library that uses
such long names oftne).
- (a variation of previous scenario) there are some auto-generated
classes that have ugly names, like perhaps ones created by jextract
(from Project Panama) and we want to use some name that is easy to
read and write
Now a section about risk of shooting yourself in the foot :)
File-level aliases for unboxed values types should retain readability
even when we look at e.g. changesets (pull requests, merge requests,
patches, etc however you name it) in a browser, without any IDE
support (so no interactive navigation, documentation, etc any type of
static analysis).
With file-level aliases, if we want to determine whether List<TypeX>
is a list of unboxed value types or not, we only need to look at
file-level aliases (for current file), if any of them defines
something like:
alias TypeX = some.package.MyValueType.val;
No need to look up the class MyValueType or anything else.
Regards,
Piotr
More information about the valhalla-spec-comments
mailing list