Explicit declaration of val types
Izz Rainy
izzeldeen03 at gmail.com
Thu Apr 28 16:15:44 UTC 2022
I second Quân Anh's suggestion to allow explicitly choosing a name for the
val type, rather than just qualifying the ref type (or vice versa) - and I
think this would be better than using a seperate modifier entirely.
1. Using a seperate declaration is just less weird than a modifier. While
other modifiers/decorations can bring in new implicit members (like
record-ness, enum-ness, or inner class static-ness), those always either
use a name chosen by the user (component name, outer class name) or a
standard name (toString, valueOf) with an explicit definition *somewhere*.
2. It makes it more clear where the val type comes from. Instead of having
"one class, two types" unlike anything else, it's just "two definitions,
two types, one is a little weird". You also get a convenient
go-to-definition target for it.
3. Neither type is "favoured" or "default" anymore - the user doesn't have
to spend extra effort reading and writing code that uses the val or ref
type, and the language no longer makes a judgement on which one you
"should" be using.
4. It makes Integer/int, Character/char, etc even less special. You can
define your own `Complex` and `complex` types, and apply everything you
already know about the built-in types to your types instead of relearning
it in terms of vals and refs.
5. Subjective, but it's just stylistically better. Helps avoid having 3
different class modifiers that all just mean "slightly more value-like",
and makes your code look more like regular java code with primitives and
boxes, especially if a lower-snake-case convention is used for val types.
You can also imagine restricting the visibility of the val type, so that
only (trusted) code internal to your library can bypass the constructor,
but it's probably better to define a seperate primitive type with less
visibility and a less visible constructor using that type.
You could also imagine allowing users to specify _ as the ref type name
when a val companion is present to just make it something.red, to allow the
author to make it very clear not to use the reference type except where
necessary (e.g. by non-universal generics), but decoupling top-level type
name from file name is probably a stretch for not much benefit.
More information about the valhalla-spec-comments
mailing list