Skip to content

[RFC] standardize constructors as: Foo.New(args) instead of newFoo(args) #34

@timotheecour

Description

@timotheecour

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):

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 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 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions