Nim
Nim copied to clipboard
Ability to define different default values on inherited objects
Summary
One of the new functionalities of Nim 2.0 will be the possibility of defining default values for fields of objects. This is a very interesting concept, however it is not at the moment usable for inherited types.
Description
At the moment, identifying inherited objects is hard. We do have the of
operator, but it’s not really useful: We can only check if an object is part of a specific sub-type, but not for example get the name if we don’t know it.
If we can have different default values for a single field, it will be trivial to know what object we are interacting with, just by looking at the assigned “identifier”.
This is especially useful if we need to create a generic procedure that needs to interact with multiple types.
Alternatives
No response
Standard Output Examples
type Macro* = ref object of RootObj
id: int = 0
type MicroOne* = ref object of Macro
id = 2
type MicroTwo* = ref object of Macro
id = 301
proc identify(obj: Macro) =
case obj.id
of 2:
echo "Object is MicroOne!"
of 301:
echo "Object is MicroTwo!"
of 0:
echo "Object is Macro!"
else:
echo "other/unknown object"
if obj.id > 300:
echo "id is higher than 300!"
identify(MicroOne())
identify(MicroTwo())
identify(Macro())
Backwards Compatibility
No response
Links
No response