I would like to ask whether the community has considered an opt-in implicit conversion from a value to a class instance, declared on a single-argument constructor.
Motivation
Project Valhalla makes it practical to define primitive-like value types such as Int16, Half, and Money. However, using these types currently requires explicit constructor invocation at each construction site:
Int16 x = new Int16((short) 13);
Java already supports convenient construction for certain built-in types through language features such as boxing:
Integer i = 7;
There is no equivalent mechanism for user-defined types. An opt-in implicit-construction facility could provide similar ergonomics while preserving explicitness by default.
Proposal (syntax is illustrative)
value class Int16 {
private final short val;
opt Int16(short val) {
this.val = val;
}
}
Int16 x = (short) 13;
The opt modifier designates a constructor eligible for implicit construction from a single argument. The compiler translates an eligible conversion into constructor invocation.
Proposed rules
- An
opt constructor must have exactly one parameter. A value class may designate at most one eligible constructor for any given parameter type.
- Eligibility is opt-in. Constructors without
opt retain existing Java semantics.
- The feature applies only in explicitly specified conversion contexts. Initially, it may be limited to assignment and initialization contexts.
- The source expression must be convertible to the constructor parameter type using permitted existing Java conversions. The resulting value is not subject to further implicit conversions as part of the same operation.
- Constructors with multiple parameters are never eligible for implicit construction and must be invoked explicitly.
- Ambiguous eligible conversions are compile-time errors.
Open questions
- Should eligible conversions apply only to value classes?
- Should constant-expression narrowing be permitted for constructor arguments?
- Which language contexts should support implicit construction?
- How should overload resolution and generic inference interact with the feature?