Search code examples
matlabconstructorimmutabilityargument-validation

Can I declare a constructor that accepts Name-Value arguments to define immutable properties?


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?


Solution

  • As of MATLAB R2024a, the example given in the question is now supported so there is no need for any workaround.