Does a function reference allocate a new object? `...
# announcements
m
Does a function reference allocate a new object?
Copy code
data class Item(val id: Int)
fun randomItem(block: (Int) -> Item) {}

// this
List(100) { randomItem(::Item) }

// vs
val constructor = ::Item
List(100) { randomItem(constructor) }
z
Easiest way to answer questions like this is do “Show kotlin bytecode” in IntelliJ
👍 1
m
I've already done it, but not knowing much about bytecode I would have appreciated an opinion from a more competent person than me. Bytecode for
::Item
is "GETSTATIC $1.INSTANCE ". From what I understand "GETSTATIC" instruction is used to get a static field value of a class, so I think it doesn't allocate a new object every time
z
Both of those are making similar GETSTATIC calls, although for fields in different classes. If you scroll to the bottom, you can see where each synthetic class is defined. It looks like each
::Item
reference generates its own class, but those classes are singletons with static instance fields.
m
I managed to find these synthetic classes and the static fields. Thanks!