How to solve type mismatch error when assigning variable to class in conditional?
23 views (last 30 days)
Show older comments
Roop
on 9 Jul 2024 at 15:38
Answered: David Fink
on 9 Jul 2024 at 18:14
Example Code:
1 flag = true;
2 if flag
3 this.prop = TFlag();
4 else
5 this.prop = FFlag();
6 end
Error Code:
Type name mismatch: TFlag ~= FFlag.
In the diagnostic report, the error is shown in line 5, where this.prop cannot be assigned FFlag() because it is understood as a varible of class type TFlag().
Question:
It appears that this.prop is being intialized as a variable of class type TFlag regardless of the condition, and I am unable to run this conditional. It should also be noted that the constructor method of each of these classes returns a struct(), but they are different sizes. TFlag returns a struct of size 30, and FFlag returns a struct of size 10.
0 Comments
Accepted Answer
David Fink
on 9 Jul 2024 at 18:14
In code generation, since the generated code is statically typed, the type of this.prop must be determined at code generation time.
When processing the first assignment to this.prop, it assigns its type as TFlag. Then when processing the second assignment, it produces the type mismatch error you observed, as FFlag is a different class type than TFlag.
It is possible to assign two distinct values with the same type, but different sizes. For example:
if runtimeCond
s = struct('f', 0); % 1x1 struct, field f = 1x1 double
this.prop = s;
else
s2 = struct('f', {1, 2}); % 1x2 struct array, field f = 1x1 double
this.prop = s2;
end
See also:
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!