y
02/25/2023, 6:31 PMtrait
(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.ephemient
02/25/2023, 6:55 PMYoussef Shoaib [MOD]
02/25/2023, 7:58 PMinterface 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
02/25/2023, 8:02 PM