vendredi 9 juin 2023

Use reflection to name methods in a generic trait in Scala

Suppose I have a generic trait that provides a way to get a value of some type (think perhaps fixtures in a test suite).

trait Fixture[A] {
    def value: A
}

Is there any way to use reflection to create a method within this trait that has the same name of the type in a concrete implementation?

So that when I can do:

class BarFoo extends Fixture[Foo] {
    override def foo: Foo = // my concrete code here
}

class BarQux extends Fixture[Qux] {
    override def qux: Qux = // create a Qux value here
}

or even worse, maybe something like:

class BarFooQux extends Fixture[Foo] with Fixture[Qux] {
    override def foo: Foo = // ...
    override def qux: Qux = // ...
}




Aucun commentaire:

Enregistrer un commentaire