How to set a default value to a map container in argument validation?
Afficher commentaires plus anciens
I'm validating a bunch of arguments in class properties. Seems quite straightfoward to set a deatault for double, integer and string datatypes.
classdef newClass < handle
properties
someStr (1,:) string = "myStr"
someNum (1,1) double = 3.1415
end
But what is the right way to do this for a map container? Because when I add this line for a map container:
someDict containers.Map
I see the following warning:

Réponse acceptée
Plus de réponses (2)
test = containers.Map
isa(test, 'handle')
Therefore if you were to pass in a container.Map to the constructor and copy what was received into a property, then the container would end up being shared with any other uses of the container.
To get around this, to get a private container.Map, you need to create the container.Map in the constructor (and make the property private and do not create any methods that can allow people to get at the container.Map). Or you could somehow clone the incoming container.Map (the class does not provide a method for copying / cloning though.)
If you want the container.Map to be shared then mark the property as Constant .
6 commentaires
Anup Kanale
le 27 Mar 2023
Walter Roberson
le 27 Mar 2023
Are you talking about setting an initial value for the property, or are you talking about default values in a arguments block for the case where the parameter is not passed to the constructor ?
Anup Kanale
le 27 Mar 2023
Walter Roberson
le 27 Mar 2023
I am not clear whether you want to deliberately share the container with the place that supplied the container, or if you want a private copy of the container ?
Anup Kanale
le 28 Mar 2023
Walter Roberson
le 30 Mar 2023
Sorry, I do not have experience with using arguments blocks.
Consider the two classes attached to this answer. The class class1936099_A defines someDict to contain a containers.Map in the properties section of the class definition. The class class1936099_B assigns someDict a containers.Map in the constructor.
obj1 = class1936099_A;
obj2 = class1936099_A;
Neither obj1 nor obj2 have 'a' as a key in their someDict property.
[isKey(obj1.someDict, 'a'), isKey(obj2.someDict, 'a')]
Let's associate 'a' with 42 in obj1's property. What does obj2's property associate 'a' with now?
obj1.someDict('a') = 42;
obj2.someDict('a')
Let's try the same with class1936099_B.
obj3 = class1936099_B;
obj4 = class1936099_B;
[isKey(obj3.someDict, 'a'), isKey(obj4.someDict, 'a')]
obj3.someDict('a') = 42;
obj4.someDict('a')
obj1 and obj2 have handles to the same containers.Map object. obj3 and obj4 have handles to different objects.
Catégories
En savoir plus sur String dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!