It would be nice to have a context-receiver "summo...
# stdlib
y
It would be nice to have a context-receiver "summoning" function in the stdlib:
Copy code
context(A) fun <A> given(): A = this@A
to be used like
given<List<String>>()
. I think this is better than the
this@
syntax since it supports generics (like
List<String>
) and can "summon" supertypes of a context receiver which gets resolved to the apt subtype context Edit: I realise that maybe stdlib can't have
context
declarations. Instead, it can be defined equivalently as:
Copy code
fun <A> A.given(): A = this
The only issue is that it pollutes the namespace of
Any.
👍 3
❤️ 3
3
e
I haven't thought about it much but would https://github.com/Kotlin/KEEP/blob/statics/proposals/statics.md be workable?
Copy code
context(T)
val T.static.context: T
    get() = this@T
List<String>.context
that would prevent things like
Copy code
f(given(), given())
from inferring types, which I would find kind of sketchy with context receivers
j
Without knowing if that works, I think
given<A>()
is more idiomatic. But the issue you mentioned can have sense
y
f(given(), given())
doesn't actually infer types. An unspecified
given()
always resolves to the closest receiver. If the closest receiver is part of a receiver group (i.e. the closest receiver is
context(A, B)
), then you get an error. Personally, I would've liked if
f(given(), given())
would've worked, but I see the ambiguity and resolution issues with it.