patterns as types
Hontvári Attila
attila at hontvari.net
Fri Jan 8 12:59:56 UTC 2021
Hello,
I have a question about the static patterns feature described in the
last published document [1]. If we have a code such as if (s instanceof
Shape.redCube(__)) { ... }, then can Shape.redCube be looked as a
"type"? Probably Shape instances are only classified by some field
values, but I feel these patterns as ad-hoc types, which could be part
of the type system (if we ignore that that they bind the extracted
values to some variables).
If they were real types, then for example we could write code like this
variable definition:
LocalDate.of(__, JANUARY, 1) firstDayOfSomeYear = ...;
So it would be explicitly specified and automatically ensured that this
variable can only contain LocalDate objects that represents the first
day of any year.
This can be probably an overkill, but the same technique can be used to
solve part of the nullability problem, if we defined a static pattern
Objects.nonNull:
class Person {
private final Objects.nonNull(String) firstName, lastName;
...
}
Combined with static imports:
import static java.lang.Objects.nonNull;
class Person {
private final nonNull(String) firstName, lastName;
...
}
And nullable String values could be assigned to the fields with an ugly
cast such as ((nonNull(String)) someName) which would throw an exception
if the value doesn't conform to the nonNull pattern. Or if the return
type of Objects.requireNonNull is changed to the pattern
nonNull(String), then it can be also used instead to get a
nonNull(String) value, in the plain old way: this.firstName =
Objects.requireNonNull(someName);
What do you think?
[1]
https://github.com/openjdk/amber-docs/blob/master/site/design-notes/pattern-match-object-model.md
More information about the amber-dev
mailing list