Search code examples
dictionarymappingsmalltalkpharo

How to map dictionary to object of specific class?


I have a given dictionary and want to map it to an object of a specific class.
All keys of the dictionary should be mapped to equally named instance variables of the object.

I guess this is a common procedure? What is the common way to accomplish it?


Solution

  • Consider doing something like this:

    dict := { #x -> 5 . #y -> 6 } asDictionary. "dictionary as you described"
    basicObj := Point basicNew. "basic instance of your object"
    
    dict keysAndValuesDo: [ :key :val |
        basicObj instVarNamed: key put: val ].
    
    ^ basicObj