-
Notifications
You must be signed in to change notification settings - Fork 23
Description
motivation
this is the analog of https://github.com/nim-lang/Nim/issues/7430 (universal conversion operator (cf D's a.to!T
) (std.conv.to)) but for constructors.
similar motivation as:
https://forum.nim-lang.org/t/703 Constructors (and tiny bit of destructors)
https://forum.nim-lang.org/t/1190/3 [RFC] Constructors proposition
in short: newFoo(args)
is not generic (hard to use in generic code given a generic type), pollutes namespace, not standard (lots of languages don't need composite names).
options that have been considered as replacement for newFoo(args)
:
-
Foo(args)
:
Foo(args) is already used for explicit conversion, eg https://forum.nim-lang.org/t/1190/1#7342 -
new Foo(args)
:
eg proposed here: https://forum.nim-lang.org/t/703/1#3885
proc new Foo(x: int): Foo = Foo(x: x)
echo new Foo(123)
but that doesn't work as new Foo
already has a meaning (GC allocation) and creates a ref Foo
, not a Foo
My proposal is the following: Foo.New(args)
Here's an example:
type
Foo=object
age:int
#instead of: proc newBar(age:int): Bar = Bar(age:age)
proc New(T: typedesc[Foo], age:int): Foo = Foo(age:age)
let a=Foo.New(100)
assert a.type is Foo
assert a.age == 100
# eg showing generic use, which would be hard using newFoo syntax
let a2 = a5.type.New(101)
# eg showing it works if all we have is an alias
type FooAlias=Foo
let a3=FooAlias.New(100)
Advantages
- no new language support needed
- backward compatible (
newFoo
constructors can be changed gradually toFoo.New
constructors, independently for each Foo) - can be used in generic code
- no namespace pollution
another advantage is it allows to define constructors for multiple types, with just 1 definition, eg:
# for example
proc New(T: isSomeTypeConstraint, arg:typed): T = ...
note
as for name to use, this can be debated , eg: instead of New
: make
, create
, ctor
etc