dm6801
01/09/2021, 8:27 AMfun main() {
fun fun1(name: String) = println("Hello $name")
val fun2 = { name: String -> println("Hello $name") }
function(::fun1)
function(fun2)
}
fun function(callback: (name: String) -> Any) {
//some complicated calculation
callback("username")
}
Which one would you use, and why?ephemient
01/09/2021, 9:02 AMval name: String?
, then I would generally prefer
fun fun1(name: String)
name?.let { fun1(it) }
over ?.run
or ::fun1
or val fun1
dm6801
01/09/2021, 9:09 AMephemient
01/09/2021, 9:16 AMfun fun1()
over val fun1 = {}
. weakly prefer function { fun1(it) }
over function(::fun1)
dm6801
01/09/2021, 9:37 AML0
LINENUMBER 7 L0
GETSTATIC Test$test1$1.INSTANCE : LTest$test1$1;
ASTORE 1
fun1 invocation:
L1
LINENUMBER 8 L1
ALOAD 0
GETSTATIC Test$test1$2.INSTANCE : LTest$test1$2;
CHECKCAST kotlin/jvm/functions/Function1
INVOKEVIRTUAL Test.func (Lkotlin/jvm/functions/Function1;)V
fun2 declaration:
L0
LINENUMBER 13 L0
GETSTATIC Test$test2$fun2$1.INSTANCE : LTest$test2$fun2$1;
CHECKCAST kotlin/jvm/functions/Function1
ASTORE 1
fun2 invocation:
L1
LINENUMBER 14 L1
ALOAD 0
ALOAD 1
INVOKEVIRTUAL Test.func (Lkotlin/jvm/functions/Function1;)V
looks like func1 has an extra GETSTATIC in the invocation phase
also, regarding your comment on function { func1(it) } vs. function(::func1) - it appears they are bytecode-equivalent,
apparently just syntactic sugar
overall, looks to me like a matter of personal preference and code stylingephemient
01/09/2021, 10:31 AM::func1
has some different metadata and serializability than { func1(it) }
- but close enough{ }
syntax is more consistent than sometimes using ::
and sometimes not due to ambiguities such as overload resolutionfun
vs val
, especially as val
is more awkward to put generics or type annotations onval
is necessary, such as
val handler = Runnable { ... }
register(handler)
unregister(handler)
when the exact same instance needs to be retained, but I have never seen that come up with Kotlin APIs, only Java interopVampire
01/09/2021, 1:59 PMdm6801
01/09/2021, 5:28 PMVampire
01/09/2021, 6:46 PMdm6801
01/09/2021, 7:23 PMVampire
01/09/2021, 7:23 PMstring randomizer
01/11/2021, 10:03 PMfunction(::fun1)
cause it much more clear that it is a callback , than
function(fun2)
however a closure is more powerful cause you can combine closures
function(fun2.then(fun3))
function {
name ->
println("Hello $name")
}
if the last param in the method is a closure you can skip the ()
Vampire
01/11/2021, 11:14 PM