Andrea Giuliano
05/04/2021, 4:48 PMfun myFancyMethod(function: () -> O)
so that a caller can use it this way:
myfancyMethod{
context.giveMeSomething() //context or it.context is available since it's set somehow from myFancyMethod
}
Is that feasible?Paul Griffith
05/04/2021, 4:51 PMfun myFancyMethod(function: Context.() -> O)
? Context
object will be this
inside myFancyMethod
call siteAndrea Giuliano
05/04/2021, 4:54 PMContext
from the caller (so outside myFancyMethod
), right?Nir
05/04/2021, 4:55 PMNir
05/04/2021, 4:55 PMNir
05/04/2021, 4:56 PMcontext
to be this
. But you could also achieve what you want, you would simply have a ContextHolder
class which has a property context
, and let ContextHolder be the receiverAndrea Giuliano
05/04/2021, 4:56 PMAndrea Giuliano
05/04/2021, 4:57 PMcontext
to be this
?Nir
05/04/2021, 4:57 PMNir
05/04/2021, 4:57 PMcontext.function()
Andrea Giuliano
05/04/2021, 4:59 PMNir
05/04/2021, 5:00 PMNir
05/04/2021, 5:00 PMNir
05/04/2021, 5:00 PMNir
05/04/2021, 5:00 PMMichael Böiers
05/04/2021, 8:48 PMwith
does. https://pl.kotl.in/tIYCr7lxXNir
05/04/2021, 9:02 PMwith
though of course you pass in the object yourself that becomes the context. the idea when writing these kotlin "DSL's" is typically that the library passes in the receiver, which lets the library have functions/properties that are only valid in certain contexts. very cool.Tobias Berger
05/05/2021, 7:45 AMfun myFancyFunction(function: (Context) -> O)
and have the context as a lambda parameter instead of this
.
And while you're at it, depending on the case, you might want to make the fancy function inline
Andrea Giuliano
05/05/2021, 7:46 AMTobias Berger
05/05/2021, 7:48 AMit
(or whatever name you define) instead of this
Tobias Berger
05/05/2021, 7:50 AMAndrea Giuliano
05/05/2021, 7:50 AMit
later in the chain?Andrea Giuliano
05/05/2021, 7:52 AMcontext ->
and you give it a name..Tobias Berger
05/05/2021, 7:52 AMAndrea Giuliano
05/05/2021, 7:52 AMAndrea Giuliano
05/05/2021, 7:53 AMMichael Böiers
05/05/2021, 7:55 AMthis
there. If it is going to be used as the parameter of other function calls, it should be the parameter of the lambda, since you would have to explicitly use this
as a parameter a lot, which doesn’t “read well”.Tobias Berger
05/05/2021, 8:07 AMNir
05/05/2021, 12:56 PMNir
05/05/2021, 12:58 PMNir
05/05/2021, 12:59 PM