Search code examples
scalatype-parameter

Instantiate class with type parameters with the type of a variable in Scala


I’ve got the following types

class Translator[To <: Language] { ... }
abstract class Language
object English extends Language
object German extends Language

Is there a way to instantiate Translator from a val that is either of type English or German?

I’m looking for something like the following (which doesn’t work):

val lang = if (someCondition) English else German
val translator = new Translator[classOf[lang]]

Solution

  • use the language as type argument in Translator constructor:

    class Translator[To <: Language](lang:To) {...}
    abstract class Language
    object English extends Language
    object German extends Language
    
    new Translator(German)
    res7: Translator[German.type] = Translator@8beab46
    
    // using class instead of object:
    class Italian extends Language
    new Translator(new Italian)
    res9: Translator[Italian] = Translator@6bc22f58