https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
s

simon.vergauwen

03/06/2023, 2:04 PM
Is there a proposal for ignoring receiver or context receiver for lambdas when passing method references? Similar to how you can pass a non-suspend method reference to a
suspend
lambda?
4
h

hfhbd

03/06/2023, 4:51 PM
How should it work if you access the context in
example
?
j

Joffrey

03/06/2023, 5:07 PM
@hfhbd the context is not provided by the
block
lambda in
example()
, it is expected by the lambda. So
example()
is actually supposed to create it and pass it to the lambda, not the other way around.
I think the question is about allowing
example(::one)
instead of forcing
example { one() }
if
one
doesn't use the context.
👌 1
h

hfhbd

03/06/2023, 5:10 PM
yeah, but what should happen if you want to execute
block
inside example without a context provided?
Copy code
fun <A> example(block: context(Fragment, View) () -> A): A { block(); TODO() }
Checking if the context is actually used could only work inside the module. Otherwise, a new version of the lib actually using the context would break the public api.
j

Joffrey

03/06/2023, 5:12 PM
I don't understand your question. `example`'s definition guarantees that
block
will be given a context (if called). So
example
has to provide one when it calls
block()
. That is irrelevant to whether callers of
example
pass a lambda that actually uses it
👍 1
Basically it is already allowed to pass a lambda that doesn't use the context:
Copy code
example { one() }
This could be simplified to
example(::one)
but the compiler is a bit too strict about the function signature to realize that it's ok.
There is no need to infer anything or detect any usage, by the way. It's just a matter of deciding that a function type without a context is sort of a subtype of the same function type but with context. Just like we do when deciding that a function without
suspend
keyword is kind of a subtype of the same function type with a
suspend
keyword.
💡 1
h

hfhbd

03/06/2023, 5:22 PM
Ah, sorry I was confused. You are absolutely right, the context is not part of the example function but of the parameter. https://pl.kotl.in/jIDDXFwHM
👍 1
e

elizarov

03/07/2023, 8:07 AM
KT-57165 Consider context conversion for callable references
s

simon.vergauwen

03/07/2023, 8:10 AM
Great, thank you @elizarov 🙏
12 Views