As much as I personally like the idea of “traits”, they’re not really necessary in Kotlin. It requires a bit more boilerplate, but you can achieve the same thing using interface delegation. For example:
Copy code
class Foo :
A by ADelegate(),
B by BDelegate()
interface A {
var a: String
}
class ADelegate : A {
override var a: String = ""
}
interface B {
var b: String
}
class BDelegate : B {
override var b: String = ""
}
b
Ben Woodworth
05/22/2023, 4:44 PM
Or possibly even nicer from the usage side, using invoke for a pseudo-constructor
Though I'd argue the Kotlin way is to prefer composition over inheritance, and do something like this
(except probably with better naming. i only used the trait-inspired naming convention for clarity)
Yeah, I find the main use case of it to be adding fields to already existing interfaces without going through every implementor and adding the override with default there