The power of Scala to implement a specific method

Is there a way to indicate that the trait should provide a concrete implementation of the method?

Given some mixin

class A extends B with C { foo() } 

The program will compile if any of A , B or C implements foo() . But how can we make, for example, B contain an implementation of foo ?

+4
source share
1 answer

You can do the following:

 class A extends B with C { super[B].foo() } 

This will be compiled only if B implements foo . Use with caution, although it (potentially) introduces some unintuitive connection. Also, if A overrides foo , there will still be B foo .

One valid use case for IMHO is conflict resolution :

 trait B { def foo() = println("B") } trait C { def foo() = println("C") } class A extends B with C { override def foo() = super[B].foo() } 

If you want B declare foo , you can use a type:

 class A extends B with C { (this:B).foo() } 

This will compile only if B declares foo (but can be implemented in C or A ).

+9
source

Source: https://habr.com/ru/post/1493320/


All Articles