MATLAB: Unexpected conversion when using property class validation

assignmentclassconversionMATLABpropertyvalidation

When attempting to restrict the set of values assignable to a property by using class validation, I find that the values being assigned are instead being converted instead of throwing an error. For example, in the following class, I would like MATLAB to throw an error when attempting to assign a negative value to Property1:
classdef Class1
properties
Property1 uint32 {isNonNeg} = uint32(0)
end
end
function isNonNeg(val)
if ~(isinteger(val) && val >= 0)
error("Property1 must be assigned a nonnegative integer value.");
end
end
However, the following code succeeds:
>> x = Class1();
>> x.Property1 = -5
x =
Class1 with properties:
Property1: 0

Best Answer

According to the documentation:
MATLAB attempts to convert the value to the specified type before running the validator functions.
This can be unexpected if the user would like to check the value being assigned before conversion. An enhancement request has been submitted to address this behavior. A workaround for now is to remove the class validation:
classdef Class1
properties
Property1 {isNonNeg} = uint32(0)
end
end
function isNonNeg(val)
if ~(isinteger(val) && val >= 0)
error("Property1 must be assigned a nonnegative integer value.");
end
end
A drawback of this workaround is that you cannot perform the conversion manually after the validator function is run.
Alternatively, you may switch to creating a setter method for the property. Note that the setter method runs after validation so you would have to totally remove property validation in order for it to work:
classdef Class1
properties
Property1
end
methods
function obj = set.Property1(obj, val)
if ~(isinteger(val) && val >= 0)
error("Property1 must be assigned a nonnegative integer value.");
else
obj.Property1 = val;
end
end
end
end