Kelvin Chung
08/11/2025, 3:26 PMinterface Extender<T> {
context(thisValue: T)
fun doSomething()
}
class Foo : Extender<Foo> {
context(thisValue: Foo)
override fun doSomething() { ... }
// So, Foo would need a context-free overload of doSomething() anyways
// passing itself as context, in order for outsiders to use it?
fun doSomething() = context(this) { doSomething() }
}
joseph_ivie
08/11/2025, 3:27 PMsealed
! I'll get you an example.joseph_ivie
08/11/2025, 3:28 PMjoseph_ivie
08/11/2025, 3:29 PMsealed interface CanOnlyBeImplementedInThisFile {}
open class CanBeSubclassed: CanOnlyBeImplementedInThisFile
Kelvin Chung
08/11/2025, 3:41 PMsealed
wouldn't work in my use case, necessarily. For an academic example, consider this:
interface InfixOp<T> {
infix fun op(rhs: T): T
}
interface InfixOpTrait<T> {
fun op(lhs: T, rhs: T): T
}
class MyType : InfixOp<MyType> {
object InfixTrait : InfixOpTrait<T> { ... }
override fun op(rhs: T) = InfixTrait.op(lhs, rhs)
}
The intent is to make InfixOp
implementable only by T
, so that you can have a "this value" available with a default implementation of InfixOp.op
, in the hope that some boilerplate could be removed. Something like
interface InfixOp2<T> {
context(thisVal: T)
infix fun op(rhs: T): T
}
joseph_ivie
08/11/2025, 3:46 PMinterface InfixOp { infix fun op(rhs: Self): Self }
Nicolai C.
08/11/2025, 3:47 PMfun <T : CharSequence> T.op() = TODO()
Kelvin Chung
08/11/2025, 3:48 PMKelvin Chung
08/11/2025, 3:49 PMinterface InfixOp3<T> {
infix fun T.op(rhs: T): T
}
That doesn't look like it does what I think it does.Nicolai C.
08/11/2025, 3:56 PMjoseph_ivie
08/11/2025, 3:59 PMComparable<T>
would ideally work?Kelvin Chung
08/11/2025, 4:00 PMKelvin Chung
08/11/2025, 4:02 PMComparable
backed by a `Comparator`" in that sense.joseph_ivie
08/11/2025, 4:02 PMKelvin Chung
08/11/2025, 4:12 PMinterface ContextedComparable<T> {
context(thisVal: T, cmp: Comparator<T>)
fun compareTo(rhs: T): Int = cmp.compare(thisVal, rhs)
}
But that just creates more boilerplate, now that I think about it. I think that a context-free Comparable
backed by a Comparator
may be crossing a line somewhere, but a context-sensitive one (which might be useful for wrapper value classes) wouldn't require that many hoops.