https://kotlinlang.org logo
Title
z

zt

05/21/2023, 5:04 AM
I'm a little confused. Intellij offers me to sometimes change lambdas to references. Is that using reflection? and isn't it bad practice to use reflection as it incurs performance loss (as i've heard)?
f

Francesc

05/21/2023, 5:11 AM
However, function references also implement function types and can be used as function literals. Such usages are not considered "real" reflection and introduce no performance overhead compared to lambda expressions
e

ephemient

05/21/2023, 5:14 AM
when inlined, there is no difference at runtime between a lambda and a function reference
when not inlined, there is a minor difference as the function reference is more specialized
Any::toString.name // "toString"
{ it: Any -> it.toString() }.name // does not compile

Any::toString == Any::toString // true
{ it: Any -> it.toString() } == { it: Any -> it.toString() } // false
but it still does not involve runtime reflection
note that invoking
toString()
on a lambda or callable reference will cause kotlin-reflect to load metadata which can be slow: https://youtrack.jetbrains.com/issue/KT-54175
z

zt

05/21/2023, 5:44 AM
Thank you both for the detailed answers. Adding on to the main question: is the same also true for a property reference? ex:
instance::foo.get()
instance::foo.set("bar")
e

ephemient

05/21/2023, 6:09 AM
similar, when inline it's the same as a lambda (e.g.
"".let(String::length)
), otherwise it involves some machinery that doesn't directly involve runtime reflection or metadata but might access that depending on what calls are made
get and set are fine