chanjungskim
05/31/2023, 1:54 AMCasey Brooks
05/31/2023, 2:08 AMa()
. The invoke
name is an operator function, it’s not typically meant to called using the actual name, just like it would be strange to see a.plus(b)
written out instead of using a + b
. The exception would be if a
is nullable, then calling the lambda like a?.invoke()
is necessary.
But a bigger reason why you don’t need to do #2 is: does it help you at all to know whether a
is a lambda or a named function? It shouldn’t, the result is the same in either case. Plus, IntelliJ colors the two differently, so you can just trust that the IDE is giving that affordance, and you don’t need to break convention to try and be more explicit.
And as a point to “clean code”, the variable name itself should let you know you’re invoking a callback rather than calling a regular function. Also, ideally, your functions should be short enough that you don’t have to scroll far to see the callback parameter in the function signature. If you can’t easily see where the callback variable is coming from, you may want to break the function up into several smaller ones.chanjungskim
05/31/2023, 2:10 AMCasey Brooks
05/31/2023, 2:49 AMCasey Brooks
05/31/2023, 2:50 AM.filter(predicate)
, .apply(block)
). block
, in particular, is very common for simple cases where you literally want to just “run a block of code” (especially when the function is inline
).
For most cases beyond that, it usually better to use coroutines and expose a suspend
function rather than calling a callback/listener like what was common in older Android/Java apps.