TomJ
TomJ

Reputation: 5469

Define Generic Types with String

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

Answers (1)

Arseniy Zhizhelev
Arseniy Zhizhelev

Reputation: 2401

  1. Look:

    def createMap[foo, bar] = {
      Map[foo, bar]()
    }
    
    val myMap = createMap[`String`, `Int`]
    

    Doesn't it look similar to the required code?

  2. 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)

  3. It seems that macros can be used. However I'm not an expert to provide the implementation.

Upvotes: 2

Related Questions