Reputation: 5469
How do you define a generic with a string? For example, if I wanted to write
def createMap(foo: String, bar: String) = {
Map[foo, bar]()
}
val myMap = createMap("String", "Int")
How could I transform foo and bar to the correct types? I'm not seeing much in the documentation about this.
Upvotes: 0
Views: 83
Reputation: 2401
Look:
def createMap[foo, bar] = {
Map[foo, bar]()
}
val myMap = createMap[`String`, `Int`]
Doesn't it look similar to the required code?
If you really wish to create a map at runtime with types unknown at compile time, then you can simply use Map[Any, Any]()
+ type casts. I don't think it is possible to achieve type safety with string type identifiers.
(To obtain a class for runtime check see another question)
It seems that macros can be used. However I'm not an expert to provide the implementation.
Upvotes: 2