Modification of Int variable from outer scope in inlined function produce a boxing into IntRef

I’m suprised that the code:

    var someValue: Int = 0
    items.forEach { item ->
        if (item.length > 3)
    print ("$someValue")

is compiling into this:

    IntRef text1 = new IntRef();
    text1.element = 0;
    Iterable itemsCount = (Iterable)items;
    Iterator index = itemsCount.iterator();

    while(index.hasNext()) {
        Object $receiver$iv =;
        String item = (String)$receiver$iv;
        if(item.length() > 3) {
            int element$iv = text1.element++;

    String var18 = String.valueOf(text1.element);

I supposed that due to inlining, a powerful optimizing feature of Kotlin, all these local variables are kept on the stack, not on the heap.

What is the reason for the instance of IntRef ?

Yes, it supposed to be so, but currently there is an optimization missing to do that.
We have an open issue in the tracker for that: KT-5248.

1 Like