Skip to content

Allow new to accept keyword arguments for more control over incomplete initialization #36789

@FedericoStra

Description

@FedericoStra

The Problem

Currently, when defining inner constructors, we can decide to incompletely initialize a structure simply by passing to new(...) fewer values than the number of fields:

struct Incomplete
    x1
    x2
    x3
    ...
    x719
    Incomplete(x1, x2, x3, x4) = new(x1, x2, x3, x4) # x5, ..., x719 are uninitialized
end

Since the call to new(...) accepts only positional arguments, this has the obvious limitation that we can only initialize a prefix of all the fields and leave the remaining ones uninitialized. It is impossible to initialize only x1, x42, x470 and x666.

The Proposal

My proposal is to allow new(...) to accept keyword arguments, so that the following code becomes legal:

struct Incomplete
    x1
    x2
    x3
    ...
    x719
    Incomplete(a, b, c, d) = new(x1=a, x42=b, x470=c, x666=d) # the other fields are uninitialized
end

Remarks

Motivation

It is just useful sometimes to be able to do this. See for instance this thread where I asked on the forum if there was a way to achieve this with the current state of the language. There are plenty of workarounds, with more or less significant downsides (complexity-wise and performance-wise), but no direct solution.

Backward compatibility

This should be 💯.

Downsides

I honestly don't see any.

Labels

design, feature, keyword arguments, types and dispatch

Metadata

Metadata

Assignees

No one assigned

    Labels

    designDesign of APIs or of the language itselffeatureIndicates new feature / enhancement requestskeyword argumentsf(x; keyword=arguments)types and dispatchTypes, subtyping and method dispatch

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions