Arjan van Wieringen
10/10/2025, 8:09 AMYoussef Shoaib [MOD]
10/10/2025, 8:31 AMinterface Monoid<M> {
val zero: M
operator fun M.plus(other: M): M
}
// Contextual bridge functions
context(m: Monoid<M>)
val <M> zero: M get() = m.zero
context(m: Monoid<M>)
operator fun <M> M.plus(other: M): M = with(m) { this@plus + other }
// Usage
context(m: Monoid<M>)
fun <M> Iterable<M>.sum() = fold(zero) { a, b -> a + b }Arjan van Wieringen
10/10/2025, 8:40 AMYoussef Shoaib [MOD]
10/10/2025, 8:42 AMobject IntMonoid: Monoid<Int> {
override val zero = 0
override fun Int.plus(other: Int) = this + other
}
The annoying part is you need to explicitly bring in IntMonoid :
context(IntMonoid) {
listOf(1, 2, 3).sum()
}Arjan van Wieringen
10/10/2025, 8:43 AMCasey Brooks
10/10/2025, 12:37 PMArjan van Wieringen
10/10/2025, 1:11 PMMyData(val delegate: Interface A) : Interface A by delegate.
But what I mean is is that I am not able to change MyData. It is external library and I only know it is class MyData.
However, I want to implement InterfaceA for it, which consists out of
interface InterfaceA {
foo(): Int
bar(): String
}
I could just create the separate extension functions:
fun MyData.foo(): Int = ...
fun MyData.bar(): Int = ...
but that still doesn't make it an Interface A.
What I would like to (pseudecode):
implement MyData : InterfaceA {
foo(): Int { ... }
ba(): Int { ... }
}
Which allows me to add an implementation of InterfaceA to MyData, even though I do not own it.
This looks a lot like Rust ofcourse:
impl MyTrait for MyData {}CLOVIS
10/13/2025, 9:06 AM// External code
interface Ext
// Your code
interface Additional
you can also:
class Wrapped(val ext: Ext) : Ext by ext, Additional {
…
}
It's essentially the same approach as Youssef's context parameters approach, but it binds the implementation in a wrapper so you don't need to pass around the context.
Then you can write a function that requires the wrapper using:
fun <T> …()… where T : Ext, T : Additional = …
However that only really works if the external object has an interface or abstract class, it doesn't work for concrete classesArjan van Wieringen
10/13/2025, 11:35 AMJP Sugarbroad
10/17/2025, 12:11 AMCLOVIS
10/17/2025, 8:07 AM@JvmInline value class implements an interface.JP Sugarbroad
10/17/2025, 7:55 PMCLOVIS
10/17/2025, 9:28 PM