With the Kotlin experimental features, is it possi...
# getting-started
k
With the Kotlin experimental features, is it possible to implement an operator overload that only works within a certain context? Something like
Copy code
interface Addition<T> {
  fun add(lhs: T, rhs: T): T
}
interface AdditionOp<T> {
  context(addition: Addition<T>)
  operator fun add(rhs: T): T = addition(this, rhs)
}
or are operator overloads locked to specific signatures and
AdditionOp.add()
is not possible?
n
Yes, that works perfectly fine, except the correct function name is
plus
not
add
. I have quite a few context-aware operator functions across a handful of my DSLs.
The only unsupported feature I've encountered so far with context parameters, is that you cannot get a callable reference to them. I'm not sure if there are plans to support them in the future, but I'd assume so.
p
You also cannot currently use them with property delegation operators (getValue)
k
Follow-up: suppose you have something like this:
Copy code
object FooAddition : Addition<Foo>

interface AdditionOp<T> {
  context(addition: Addition<T>)
  operator fun plus(rhs: T): T = ...
}

class Foo : AdditionOp<Foo>
Given that
FooAddition
is a globally available singleton, would it be possible to invoke the
+
operator "context-free"? ie. without
Copy code
context(FooAddition) { ... }
I imagine that this could be useful in certain situations involving value classes.
🚫 1