1

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

3 Answers 3

5

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

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

3 Comments

Thank you for the quick answer. Your second point was a mistake in my code. I fixed it. I just removed too much of the boilerplate to clarify my issue. I am not sure what the problem is with English and German not being classes.
Ok, I changed my answer accordingly. But the point is: is there a good reason to use generic types here ?
You can’t know why I’m actually using generic types here. In my code every language has its own apply method, which itself has a generic type. This type defines a enumeration of Terms that can be translated by the Translator. So actually the Translator has a second type parameter, that applies to its apply method.
3

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

1 Comment

I prefer this answer since it still uses generic types.
0

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]

1 Comment

The answer is correct but doesn’t answer my question (val).

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.