With the new context receivers, is there a differe...
# stdlib
o
With the new context receivers, is there a difference between:
Copy code
context(Foo)
fun bar() {
    ...
}
and
Copy code
fun Foo.bar() {
    ...
}
? If not, will the 2nd way of writing be eventually deprecated?
w
There is a difference in that context receivers will not change the explicit
this
receiver within the block, and I don’t recall that the functions with receivers would be deprecated
you can read about the feature in detail here: https://github.com/Kotlin/KEEP/blob/master/proposals/context-receivers.md, there’s a section on
this
behavior and an explicit suggestion to not use context receivers and functions with receivers interchangeably. But I don’t see an explicit comparison between the two
(also btw there’s #language-evolution channel which might be more appropriate for this question)
o
I just feel like it would be awkward for fun Foo.bar() to exist at the same time while context(Foo) fun bar() exists also
w
they mean different things though
Even though both declarations are similar in many aspects, and their bodies look similar, the declaration of
fun User.updateNow()
is explicit about the intent to perform an action on the
User
object.
d
Extension and context receivers are differently processed during call resolution. Also you can not call function with context receiver on explicit receiver
Copy code
fun Foo.bar_1() {}

context(Foo)
fun bar_2() {}

fun test(foo: Foo) {
    foo.bar_1() // ok
    foo.bar_2() // error
    with (foo) {
        bar_1() // ok
        bar_2() // ok
    }
}
o
@dmitriy.novozhilov ok interesting. Didn't know foo.bar_2() would fail