How to implement a setter restriction?
이전 댓글 표시
When making a user-defined class myClass that inherits from matlab.mixin.SetGet, how can I restrict the Set for a property prop1? Say that I want to allow only true/false sets for a property.
classdef myClass < handle & matlab.mixin.SetGet
properties (Access = public)
prop1
end
methods
%% Setter restrictions
% This is what I would do if it weren't a subclass of matlab.mixin.SetGet {
function set.prop1(self,value)
% Prevent non-boolean input value sets.
if value == true
self.prop1 = true;
else
self.prop1 = false;
end
end
%}
end
end
I like the syntax of matlab.mixin.SetGet so I'd prefer to not code it this way.
댓글 수: 5
Walter Roberson
2019년 1월 31일
assert(isscalar(value) && islogical(value), 'Must be boolean scalar')
I would note, though, that it is very common for people to pass 0 for false or 1 for true, and that as far as MATLAB is concerned, anything non-zero non-nan is true.
Dominik Mattioli
2019년 1월 31일
Walter Roberson
2019년 1월 31일
It would go right after
% Prevent non-boolean input value sets.
Are you hoping for a mechanism to add type restrictions on the calls themselves, such as (hypothetically) through the methods attributes list, so that MATLAB does the type filtering for you, without you having to put in a type check yourself ?
Dominik Mattioli
2019년 1월 31일
Walter Roberson
2019년 1월 31일
If you want to permit 0 and 1 as well as true and false, then I note that ismember() of 0 or 1 against true false works, and ismember() of true or false against 0 1 works, and that true == 1 and 0 == false work.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!