https://kotlinlang.org logo
#getting-started
Title
# getting-started
y

y

03/23/2023, 4:14 PM
I don't understand interfaces with extension functions. say I have
Copy code
class Foo(val s: String)

interface MyInterface {
    fun Foo.bar(): String
}

object MyImpl : MyInterface {
    override fun Foo.bar(): String = this.s
}
then given
val myImpl = MyImpl
and an instance of
Foo
, how/when can I call `MyImpl`'s implementation of
bar()
?
p

Paul Griffith

03/23/2023, 4:20 PM
Copy code
with(MyImpl) {
  someFooInstance.bar()
}
y

y

03/23/2023, 4:25 PM
oh! that's really cool. so the
when
block brings all the extension functions of
MyImpl
into scope?
just wanted to say again that this is really cool
p

Paul Griffith

03/23/2023, 4:29 PM
per https://github.com/Kotlin/KEEP/blob/master/proposals/context-receivers.md#introduction (recommended reading, especially w.r.t the future of multiple receivers in Kotlin) in this example,
MyInterface/MyImpl
is the ‘dispatch receiver’ and
Foo.bar
is the ‘extension receiver’
❤️ 1
3 Views