How to match a dictionary for an object of a particular class?

I have this dictionary and want to map it to an object of a particular class.
All dictionary keys must be matched by the same named instance variable of the object.

I assume this is a normal procedure? What is the general way to achieve it?

+4
source share
2 answers

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
+6
source

This is a really generic template. It is often used in serialization and materialization. You can find an implementation in STON

+3
source

Source: https://habr.com/ru/post/1627038/


All Articles