You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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):
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.typeis Foo
assert a.age ==100# eg showing generic use, which would be hard using newFoo syntaxlet a2 = a5.type.New(101)
# eg showing it works if all we have is an aliastype FooAlias=Foo
let a3=FooAlias.New(100)
Advantages
no new language support needed
backward compatible (newFoo constructors can be changed gradually to Foo.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 exampleproc New(T: isSomeTypeConstraint, arg:typed): T =...
note
as for name to use, this can be debated , eg: instead of New: make, create, ctor etc