Skip to content

keyword argument constructor for immutables #5333

Closed as not planned
Closed as not planned
@Keno

Description

@Keno

@JeffBezanson and I were discussing adding a second default constructor with the semantics

immutable foo
bar::Int
baz::Int
# this is the usual default constructor
foo(bar,baz) = new(bar,baz)
# I am proposing this in addition
foo(x::foo;bar=nothing,baz=nothing) = 
    foo(bar === nothing ? x.bar : bar, baz === nothing ? x.baz : baz)
end

This would cover the case where you want to obtain a new value with one field changed e.g. in the example above

julia> foo(1,2)
foo(1,2)

julia> foo(ans,baz=3)
foo(1,3)

This is especially useful when the immutable has a lot of field. One example that comes to mind and where I already define a constructor like the above is URIParser.jl

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions