Setting properties of custom class objects that are dictionary values, where the dictionary is a protected property of another class

12 views (last 30 days)
I am exploring different ways to use OOP in Matlab. I set it up as follows
classdef A_test < handle
properties (GetAccess = public, SetAccess = protected)
B
db
dc
end
methods
function obj = A_test()
obj.B = B_test;
obj.B.value = 'z';
obj.db = dictionary;
obj.db(1) = B_test();
obj.db(1).value = 'x';
obj.dc = dictionary;
obj.dc(1) = C_test();
obj.dc(1).set_value('y');
end
end
end
classdef B_test < handle
properties (Access = public, SetObservable, Dependent)
value
end
properties(Access = private)
value_
end
methods
function val = get.value(obj)
val = obj.value_;
end
function obj = set.value(obj,val)
% input checking
obj.value_ = val;
end
end
end
classdef C_test < handle
properties (Access = public)
value
end
methods
function obj = C_test()
end
function obj = set_value(obj,val)
% input checking
obj.value = val;
end
end
end
I am able to set A.B.value, but A.d(1).value throws an error (but it actually does set the value successfully):
A.d(1).value = 'z'
Unable to set the 'd' property of class 'A_test' because it is read-only.
I think this is because the dictionary tries to update its hash table when a value changes. However, the third way, C_test, works with no errors, so that doesn't totally make sense. What is going on here? I would like to use B_test if possible.
Edit: Code to run the test cases:
A = A_test();
A.B.value = 'q';
A.B.value
A.dc(1).set_value('r');
A.dc(1).value
A.db(1).value = 'p';
A.db(1).value

Answers (0)

Products


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!