RFCs
RFCs copied to clipboard
compiler support for object construction shorthand (full fields initializer)
Motivation
The Nim language supports named field names with values to construct an object. It works perfectly fine and is unambiguous, since it's different from function calls or type conversions syntactically.
type
Vector = object
x, y, z: int
var x = Vector(x: 1, y: 2, z: 3)
However, compared to function calls which support both named and positional parameters, this way of construction seems not to be succinct and looks redundant. Indeed, it is. The field names are not actually needed, which means we can construct the object using unnamed field values. var x = Vector(1, 2, 3)
just works. Why not add a shorthand for the object construction and call it a day?
Description
This RFC proposes a new way of object construction, which makes it handy to construct objects. You can mix it with named field values.
type
Vector = object
x, y, z: int
var x = Vector(1, 2, 3)
var y = Vector(1, y: 2, z)
All the fields need to be initialized in order. It means all cases below should give a proper error message (it might be relaxed in the future).
var x = Vector(1, 2)
var y = Vector(1, z: 3)
var y = Vector(1, y: 2)
var y = Vector(1, z: 3, y: 2)
As to object variants, the discriminator must be known at the compile time because the compiler needs to get hold of the exact selected branch. In the case below, the value of flag
should be a constant.
type
Ciao = object
id: int
case flag: bool
of true:
num: int
of false:
done: bool
name: string
var x = Ciao(12, true, 1, "123")
For historic reasons, an object with a single field cannot be initialized with an unnamed field value. It should always be interpreted as type conversions. The field name needs to be written explicitly in order to construct an object.
type
Single = object
id: int
# var s = Single(12) # which gives type mismatch errors
var s = Single(id: 12)
Backwards Compatibility
It can start from an experimental feature. It might disturb function calls with the same name as the type from other modules, which means the object construction shorthand might take precedence over function calls.