https://kotlinlang.org logo
#getting-started
Title
# getting-started
y

y

02/25/2023, 6:31 PM
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

ephemient

02/25/2023, 6:55 PM
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

Youssef Shoaib [MOD]

02/25/2023, 7:58 PM
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

y

02/25/2023, 8:02 PM
that… looks quite good. thanks a lot. I’ll give it a try and see how it works for my use case.
7 Views