In Scala, suppose classes A and B that has a common method, but not inherited any common interface:
class A {
def foo() {
println("A.foo")
}
}
class B {
def foo() {
println("B.foo")
}
}
What I want to do is to define a trait that extends any classes that has foo() method. I tried this:
type Fooable = {
def foo()
}
trait Q extends Fooable {
override def foo() {
println("before super.foo")
super.foo()
println("after super.foo")
}
}
(new A with Q).foo()
(new B with Q).foo()
However, Scala compiler rejects this code with an error:
error: class type required but AnyRef{def foo(): Unit} found trait Q extends Fooable {
The best solution is to make an interface that contains common methods and modify classes A and B to inherit the interface. Unfortunately, we cannot modify these classes. This is common in Java libraries such as:
java.sql.Connection.close()andjava.io.Closeable.close()android.app.Activity.onDestroy()andandroid.app.Service.onDestroy()
You can’t do it. Here’s the fundamental problem with it, quoting you:
Scala demands that the class hierarchy to be a tree, which means any element in it will have one, and just one, parent class. It can have many parent traits, and many ancestor classes, but what you ask for is strictly against the hierarchy demanded by Scala.
Now, you are mixing two concepts here: nominal typing, where the type of something is defined by its class or trait, and structural typing, where the type of something is defined by what methods it implements.
Nominal typing and structural typing are, however, rather incompatible. In fact, before Scala it was generally agreed on that the two could not cooexist and, in fact, Scala has a very limited version of structural typing. You could do something like this:
Or you could combine structural types with self types, like this:
But you cannot inherit from a structural type, as inheritance is a characteristic exclusive of nominal types. And, because you cannot inherit a structural type, you cannot override it, or call it on an ancestor, which means
trait Qcannot declare an override onfoo().