Inheritance of the same name from distinguishing features

I have a trait that extends two other traits that have the same name for the function, but it is slightly different from the inside, I want to know how to find out which function will be called?

I have a trait B that has print() and trait C that has print() if I inherit them both as follows:

 trait A extends B with C { def print() } 

Does each print print something else whose print will be called up?

+6
source share
3 answers

In the specific case, when you have name conflicts, you will get a compile-time error. Assuming D is an implementing class:

 class D extends A with C with B def main(args: Array[String]): Unit = { val d = new D println(d.print()) } 

You will see:

 Error:(25, 9) class D inherits conflicting members: method print in trait B of type ()Unit and method print in trait C of type ()Unit (Note: this can be resolved by declaring an override in class D.) class D extends A with B with C 

However, if we help the compiler by adding override print() to D and calling it super.print() , it will print the last sign in the line that supports the print method, that is:

 trait A { } trait B { def print() = println("hello") } trait C { def print() = println("world") } class D extends A with B with C { override def print(): Unit = super.print() } 

We will get the "world". If we switched B and C :

 class D extends A with C with B { override def print(): Unit = super.print() } 

We would get a hello.

+6
source

One of the most important features of the traits in the original book by Schärli, Ducassé, Nierstrasz, Black is the resolution of conflicts by renaming and hiding. This feature is completely absent in Scala Traits.

In Scala, conflicts are simply not resolved. They are recognized and rejected by the type system. (The original article was in the context of Smalltalk, which has no type system, so a different approach was used.)

+1
source

The scala compiler gives you a compilation error.

Why don't you see this on your own using the Scala REPL.

 scala> trait B { def print(): Unit = println("B") } defined trait B scala> trait C { def print(): Unit = println("C") } defined trait C scala> trait A extends B with C { def foo = print() } cmd11.sc:1: trait A inherits conflicting members: method print in trait B of type ()Unit and method print in trait C of type ()Unit (Note: this can be resolved by declaring an override in trait A.) trait A extends B with C { def foo = print() } ^ Compilation Failed 

I think you can easily understand using a compiler error

0
source

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


All Articles