https://kotlinlang.org logo
#announcements
Title
# announcements
w

wasyl

12/05/2019, 11:19 AM
Is using function references in any way different than wrapping calls in lambdas? For example with
Copy code
fun doSomething(param: String)
fun foo(param: String) 

foo { doSomething(it) }
vs
foo(::doSomething)
vs
foo(instance::doSomething)
is bytecode for either option more efficient for example?
j

jimn

12/05/2019, 11:53 AM
the parser might do less work, but not likely any benefit
w

wasyl

12/05/2019, 12:09 PM
For some reason I thought there might be, perhaps only on some JVM targets. Or maybe only on Android with R8 optimizations?
j

jimn

12/05/2019, 12:10 PM
Kotlin doesn't have AOP, i don't think there is any way to make the variations mean unseen things.
in c++ an operator overloaded pointer or reference could create a completely different effect.
caviat emptor, compiler extensions might impose differences
r

Ruckus

12/05/2019, 2:41 PM
There are a couple of differences to watch out for. For example:
Copy code
var string: String = "a"
val f1: () -> Int = { string.length }
val f2: () -> Int = string::length
println(f1())  // 1
println(f2())  // 1
string = "aaa"
println(f1())  // 3
println(f2())  // 1
👍 2
w

wasyl

12/05/2019, 2:55 PM
That’s right, I also got a NPE once because the receiver wasn’t yet initialized, too. So it does change something, but function reference still creates the same lambda as writing it manually?
2 Views