pvorb
pvorb

Reputation: 7289

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]]

Upvotes: 1

Views: 326

Answers (3)

drexin
drexin

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

Nicolas
Nicolas

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

Johnny Everson
Johnny Everson

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

Related Questions