Reputation: 7289
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]]
Upvotes: 1
Views: 326
Reputation: 24403
Just instantiate Translator
with the type of German
or English
like this:
new Translator[German.type]
edit:
or from a val
val x = German
new Translator[x.type]
Upvotes: 0
Reputation: 24769
The issue is that neither English
or German
are classes. Are you sure that you need genericity here? Maybe composition is sufficient. A possible solution is:
val lang = Translator(if (someCondition) English else German)
with the following classes and objects:
case class Translator(l: Language)
trait Language
object English extends Language
object German extends Language
But it's a quite different design than the one you expected...
Upvotes: 5
Reputation: 8601
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
Upvotes: 3