2

Since MATLAB R2019b it has been possible to declare name-value arguments from class properties which has created an elegant way to define a class that can be constructed with a declaration of its properties without repeating each defined property in the code for the constructor:

classdef C < handle & matlab.mixin.SetGet
    properties
       Prop
    end
    
    methods
        function obj = C(props)
            arguments
                props.?C
            end
            set(obj,props)
        end
    end
end

Which than can then be instantiated thus:

>> C(Prop = 1)

ans =

  C with properties:
  
    Prop: 1

If instead I need the properties to be immutable, it becomes less clear how to neatly do this. Simply changing properties to properties (SetAccess = immutable) is no good, because the .? syntax only seems to support public settable properties, so attempts to instantiate then result in the error:

Error using C
Invalid argument list. Function 'C constructor' does not accept input arguments because class 'C' referenced in the arguments block does not have public settable properties.

In this case, one could explicitly declare props.Prop as a name-value constructor argument instead, and assign each property one-by-one to the object, but this code coupling becomes more bloated and unmaintainable as the class properties become more numerous.

Is there a more direct way?

Will
  • 1,835
  • 10
  • 21

1 Answers1

1

For classes with no other repeating arguments to the constructor, the Name-Value argument pattern can be replicated by defining repeating arguments and the values assigned using dynamic subscripting:

classdef C < handle
    properties (SetAccess = immutable)
       Prop
    end
    
    methods
        function obj = C(name,value)
            arguments (Repeating)
                name (1,1) string
                value
            end

            for ii = 1:numel(name)
                obj.(name{ii}) = value{ii};
            end
        end
    end
end

Unlike the .? syntax with public-settable properties that assigns arguments to a struct, this can't be combined with other repeating arguments to the constructor, so doesn't allow for as flexible a function signature but will fill what seems otherwise to be a gap in many cases.

Will
  • 1,835
  • 10
  • 21