I have a question for how you call callback param....
# compose
c
I have a question for how you call callback param. Which one do you prefer or are you using something else? 1. just call a() 2. call a.invoke() For me, calling invoke() can distinguish from normal function so, I always use the second way. How about you guys?
1️⃣ 2
c
Just call
a()
. 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.
c
@Casey Brooks Thanks for the answer. May I ask you how you name them? And my IDE doesn't show me anything, may I ask you how you set the feature?
c
Turns out I was remembering the coloring a bit incorrectly. I was thinking that calling class functions were different from paramters, but it’s actually top-level functions which are italicized and class-level properties that are colored. Sorry about that.
For naming, it’s most helpful to look at the naming of stuff in the stdlib. For its lambda paramters, they typically use short, 1-word parameter names (
.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.