in Rust, I can define a `trait` (which roughly tra...
# getting-started
y
in Rust, I can define a
trait
(which roughly translated to a Kotlin
interface
), and then implement that
trait
for types which were defined elsewhere. can I do something similar in Kotlin? I know I can kind of simulate this with extension functions.
e
that wouldn't be compatible with the Java object model
depending on what you're trying to do, you might be able to simulate it with extension functions, or possibly context receivers
y
Context receivers are aboslutely the way to go here. Here's an example of how they can be used:
Copy code
interface Summable<T> { // similar to a trait Summable that is implemented for some type T
    operator fun T.plus(other: T)
    val zero: T
}

// You can even define methods that need T to be summable
context(Summable<T>)
fun <T> List<T>.sumAll(): T = fold(zero) { acc, t -> t + acc }

// implementing Summable for a type is trivial
object IntSummable: Summable<Int> {
    override val zero = 0
    override fun Int.plus(other: Int) = this + other
}

//usage is slightly ugly in that you have to explicitly bring the implementation of Summable<Int> into scope

with(IntSummable) {
    listOf(1, 2, 3, 4, 5).sumAll()
}
y
that… looks quite good. thanks a lot. I’ll give it a try and see how it works for my use case.