Reputation: 2376
I have a hash map which acts as store of objects - where key is class name & value is object
store = {} of String => Type
store["Animal"]= Animal.new
store["Book"]= Book.new
store["Car"]= Car.new
Here class is unknown to me, which means i can't use union type. Please tell me how to solve this problem ?
I am trying to create a wrapper around hash map for storage of objects, which will save object & return object by key.
Update 1
Classes will be passed as a parameter - like this
add_in_store(Animal)
add_in_store(Person)
Update 2
Crystal play link of what i am trying to do - https://play.crystal-lang.org/#/r/8lwx
Solution of problem doesn't have to be in same way as what i m doing. It can be with any other approach like using proc or macro etc.
Upvotes: 0
Views: 429
Reputation: 4857
Hash
is a generic type, to wrap it in a way where you cannot or don't want to restrict the possible types of the generic arguments, you should make your wrapper itself generic.
class Store(V)
@store = {} of String => V
def add(name, value : V)
@store[name] = value
end
end
Then the consumer of your wrapper has to give the possible types.
Upvotes: 1