Scala vs. Kotlin: Multiple Inheritance and the Diamond Problem
While Java doesn't allow multiple inheritance, here is how Kotlin and Scala can offer some of the functionality while avoiding the diamond problem.
Join the DZone community and get the full member experience.
Join For FreeInheritance is one of the basic tenets of Object-Oriented Programming, along with encapsulation and polymorphism. Alongside simple inheritance, there is multiple inheritance:
— Wikipedia
C++ is famous for allowing multiple inheritance and describing the diamond problem. It states that there’s an issue when a child class inherits from multiple classes that have the same method.
C++ has its own way of coping with the diamond problem. In order to avoid it, Java completely disallows multiple-inheritance. Let’s check how Scala and Kotlin fare.
Scala
Scala doesn’t allow for multiple inheritance per se, but allows us to extend multiple traits.
— Scala Documentation
The above diagram translates into the following code:
trait Openable {
def open() { ... }
}
trait Window extends Openable {
def open() { ... }
}
trait Door extends Openable {
def open() { ... }
}
class WindowDoor extends Door with Window {
...
}
Scala resolves the diamond problem by defining one main super trait, whose code will be used, among all super traits. The main one is set with the extends
keyword, while the others are set with with
.
Hence, in the above example, WindowDoor.open()
will, by default, use code from Door.open()
. Of course, nothing prevents us from overriding the method.
Kotlin
As in Scala, Kotlin doesn’t allow us to extend multiple super classes. Yet, interfaces can have concrete functions.
— Kotlin Documentation
The following is the code above translated in Kotlin:
interface Openable {
fun open() { ... }
}
interface Window : Openable {
override fun open() { ... }
}
interface Door : Openable {
override fun open() { ... }
}
class WindowDoor : Door, Window {
override fun open() { ... }
}
Kotlin takes another path to solve the diamond problem: explicit overriding. The compiler detects diamond occurrences, and fires an error if a function is implemented by multiple parent classes. To fix this, the developer must explicitly code the desired behavior.
Conclusion
While Scala’s approach is more elegant, Kotlin’s is consistent with its philosophy: being explicit and readable before being concise.
Published at DZone with permission of Nicolas Fränkel, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments