In Kotlin we'll have possibility to create a "trait that may require a class being extended on the call side", like
class Bar {}
trait T1 : Bar {}
class Foo : Bar, T1, T2, T3 {}
class Wrong : T1, T2 //error: Wrong should extend Bar
I can't imagine any flow where I can apply this structure. Can anyone tell me why we need it?
In Kotlin, interfaces are traits (historically even keyword trait was used instead of interface ). In practice, it means that we can define default bodies for methods and declare properties (but without any actual values so they still have to be overridden in a non-abstract class): interface NumberHolder {
A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits.
Kotlin interfaces are similar to abstract classes. However, interfaces cannot store state whereas abstract classes can. Meaning, interface may have property but it needs to be abstract or has to provide accessor implementations. Whereas, it's not mandatory for property of an abstract class to be abstract.
Traits are reusable components representing a set of methods or behaviors that we can use to extend the functionality of multiple classes. For this reason, they're considered as interfaces, carrying both default implementations and state. All traits are defined using the trait keyword.
I think the main reason for this is to allow the trait to make use of methods and properties defined in the concrete class. Imagine that Bar
had some basic method that other convenience methods could be built on top of... by having the trait require that it be used on subclasses of Bar
, you could define methods in the trait that call that method. You could then provide those methods to many subclasses by giving them the trait.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With