0

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.

4
  • The whole point of generics is to be type-safe at compile time. You're trying to defeat that. Commented Aug 13, 2013 at 20:21
  • 1
    And what would you expect the return type of createMap to be, then? Commented Aug 13, 2013 at 20:29
  • You could use macros to do that (I'll give you an example if you need it), but know that the strings then must be literals in order for it to work. Please describe your use case, we might give you another solution. Commented Aug 13, 2013 at 20:59
  • Use case: Map[Foo,Bar](f->Bar(f)), where Foo and Bar are classes to be loaded (by context loader or implicit param), hence, createMap("Foo", "Bar")("foo"). You can create a mirror for the class loader; can you import the symbols into currentMirror to operate on them usefully? So, yes, reflection is trying to defeat a facile distinction between compile-time and run-time type safety. Just ask ClassTag. Commented Aug 13, 2013 at 21:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for just replacing stuff in the example. Especially the back-ticks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.