Slide 21
Slide 21 text
interface Monoid {
val unit: T
fun T.combine(that: T): T
}
object IntMonoid: Monoid {
override val unit: Int = 0
override fun Int.combine(that: Int): Int = this + that
}
context(Monoid)
fun List.sum(): T = fold(unit) { acc, e -> acc.combine(e) }
with(IntMonoid) {
val sum = listOf(1, 2, 3).sum()
println(sum) // 6
}
参考 https://github.com/Kotlin/KEEP/blob/context-receivers/proposals/context-receivers.md#use-cases