abreslav ha scritto:
It was conceived as means of decomposing biggish classes and having traits as mixable-in behaviors in a big hierarchy: see this paper http://www.ptidej.net/courses/ift6251/fall06/presentations/061122/061122.doc.pdf
This feature is indeed questionable: the benefits are smallish, and the concept may be hard to grasp and implement. We are considering removing it before 1.0
Oh, I’ve read (and sometimes cited) that paper! I also see that problems arise from the fact that Smalltalk is dynamically-typed programming language, while Kotlin is statically-typed, thus, assumptions that they make there cannot be made here.
e.g., a trait may require arbitrary members to be available, while, in Kotlin, the required members must be declared somewhere.
As you probably already know, Scala(*) overcomes this by also supporting structural typing (that is, for people who may not know, you can basically require an unnamed type in terms of the members you expect it to have e.g. “some type with a member fun foo(): Unit”), but I’m quite certain that you do not want that kind of complexity in Kotlin.
I’m now seeing where the idea of a class requirement may come from, but I think that would really tightly couple the trait hierarchy with a class hierarchy, which I feel like it would hinder the benefits of traits altogether. What I would rather do is what @maaartinus is suggesting in his own post; that is, define an ad-hoc trait and code against that, rather than actually requiring the class. This would still fit the original trait model(**).
e.g. Class = Superclass + State + t1 + t2 + Glue
I see no problem with State being implemented by the last class in the chain (together with the Glue), e.g.
open class SuperClass(val someInt: Int)
trait Requirements {
val someInt: Int
}
trait T1 {
val otherState: Int
}
trait T2: Requirements
class LastClass: SuperClass(100), T1, T2 {
val otherState = 20
}
(*) whose particular flavor of traits is kind of different from that described in the original paper; but then again, Scala is not Smalltalk
(**) for people who may be interested in this topic, Chapter 8 of Schärli’s PhD thesis, which came after the paper, discusses other trait implementations, even in statically-typed contexts http://scg.unibe.ch/archive/phd/schaerli-phd.pdf