Is is possible to require a context receiver for a...
# getting-started
j
Is is possible to require a context receiver for a lambda? Those do not work:
Copy code
context(String)
val foo = {
    println(toString())
}
Copy code
val foo = context(String) {
    println(toString())
}
r
Would this work?
Copy code
context(String)
val foo get() = {
    println(toString())
	}
Otherwise it's not really clear what you're trying to achieve
c
It's declared in the type:
Copy code
val foo: context(String) () -> Unit = {
    println(toString())
}
j
Sorry @Robert Williams, I did not explain enough, I want to accept a lambda with a context receiver as a parameter of my function. Thanks to @CLOVIS I now understand how to do this.
So I've tried this:
Copy code
val print: context(String) () -> Unit = {
    println(toString())
}
It works well but I cannot call it with a context receiver:
Copy code
with("hello") {
    print()
    //   ^ Error: No value passed for parameter 'p1' 
}
I must pass the context as a parameter:
Copy code
print("hello")
Is this the only way?
c
I'm not sure. Maybe it's a bug of the current implementation? It is just a prototype, after all. It seems similar to the behavior of regular receivers, where lambdas can accept them as regular parameters instead.
j
It seems similar to the behavior of regular receivers, where lambdas can accept them as regular parameters instead.
Oh I did not know that actually!
c
But in the case of regular receivers, it's optional: you can pass it either as receiver or as a parameter
j
It is just a prototype, after all.
Yeah, I'm okay with this and I'm not expecting much. I'm just taking a look at context receivers to explain to people why we can't use them right now 😅
👍 1
But I do not want to say stupid things, so I try and learn 😛
Thank you for your answers 🙇‍♂️
c
That's the best approach! Have fun learning 🙂
K 2
y
Calling contextual lambdas like that is a current limitation of the prototype. One easy way to get over it is to do:
Copy code
context(A) operator fun <A, R> (context(A) () -> R).invoke(): R = this(this@A)
🤯 1
j
That’s a nice workaround, thank you!