patterns as types
Remi Forax
forax at univ-mlv.fr
Tue Jan 12 16:53:00 UTC 2021
----- Mail original -----
> De: "Hontvári Attila" <attila at hontvari.net>
> À: "amber-dev" <amber-dev at openjdk.java.net>
> Envoyé: Vendredi 8 Janvier 2021 13:59:56
> Objet: patterns as types
> 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).
Shape.redCube(_) is not a type, because the pattern requires to call the pattern method redCube() inside the class Shape at runtime,
so you only know if the shape is a red cube at runtime and not at compile time.
>
> 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?
You are moving the requireNonNull from each call site to one declaration site which isgood but at the same time, you will not have any error at compile time like in Kotlin / C#, which is bad.
>
>
> [1]
> https://github.com/openjdk/amber-docs/blob/master/site/design-notes/pattern-match-object-model.md
regards,
Rémi
More information about the amber-dev
mailing list