Mark
02/21/2022, 9:18 AMval lambda = if (myClickHandler == null) null else {
myClickHandler::onClick
}
I wish this was possible:
myClickHandler?::onClick
Joffrey
02/21/2022, 9:19 AMif
statements with:
val lambda = myClickHandler?.let { it::onclick }
In general if the expression in the non-null case takes the object you're testing as receiver, you could just use ?
, as in thing?.propertyOrFun
. But if the object you're testing is used as something else in the non-null case (not a simple receiver), you can always use let
as shown above. Whether it's more readable than a plain if
depends on the expression IMO.
You can see ?let { .. }
on a nullable value like a map
call on an Optional.Mark
02/21/2022, 9:29 AMmyClickHandler?.let(MyClickHandler::onClick)
Regardless, it’s a shame this is not possible:
myClickHandler?::onClick
Mark
02/21/2022, 9:49 AMmyClickHandler?.toLambda(MyClickHandler::onClick)
fun <T> MyClickHandler.toLambda(lambda: MyClickHandler.(T) -> Unit): (T) -> Unit =
{ this.lambda(it) }
but I really want to have a more generic type for lambda
.Joffrey
02/21/2022, 9:51 AMlet
expects a function that transforms its argument (the receiver of let
) into whatever you want as return value of the whole let
call. MyClickHandler::onClick
is a function that takes an instance of MyClickHandler
AND whatever input onClick
takes, and returns the result of onClick
. This is quite different. If it compiled, you wouldn't get a function out of that let(MyClickHandler::onClick)
call, but a simple value that's the return value of onClick
Joffrey
02/21/2022, 9:54 AMtoLambda
could be interesting in general, but I think in this case it just adds more complexity. If the contributors are familiar with Kotlin and let
, the expression with let
has less cognitive overhead IMOJoffrey
02/21/2022, 9:55 AMtoLambda
is a bit strange, as there is no lambda in the caller's syntax in the end. You just get an instance of a function type, while a lambda would be a { .. }
literal.Mark
02/21/2022, 9:57 AMJoffrey
02/21/2022, 10:00 AMMark
02/21/2022, 10:03 AMJoffrey
02/21/2022, 10:06 AMtoLambda
, but from the caller's point of view there is no lambda (it could have been implemented with an anonymous function and still yield the same function result)Mark
02/21/2022, 10:09 AMtoNotNullFunction(nullableFunction: ...)
?Joffrey
02/21/2022, 10:18 AMJoffrey
02/21/2022, 10:19 AMMark
02/21/2022, 10:23 AMJoffrey
02/21/2022, 10:49 AMMark
02/21/2022, 10:59 AMJoffrey
02/21/2022, 11:08 AM?.let { it::onClick }
when you need to pass a single function from the bigger nullable multi-function handler instance.Mark
02/21/2022, 11:10 AMJoffrey
02/21/2022, 11:32 AMMark
02/22/2022, 1:19 AMYoussef Shoaib [MOD]
02/23/2022, 5:27 PMbindReceiver
would probably be a good name for the toLambda
function because that's really what it's doing, it binds your myClickHandler
to the passed-in function, and it is just that the bindReceiver
function happens conditionally