Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding traits in Kotlin

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?

like image 987
Stan Kurilin Avatar asked Dec 10 '11 15:12

Stan Kurilin


People also ask

What is trait in Kotlin?

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 {

What is trait in spark?

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.

What is the difference between abstract class and interface in Kotlin?

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.

What is groovy trait?

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.


1 Answers

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.

like image 94
ColinD Avatar answered Oct 04 '22 21:10

ColinD