3

I'm trying to understand how to use inline modifier correctly. I understand general case, when we inlining lambda to prevent excess allocation, as described in docs.

I was inspecting kotlin stdlib and found in _Strings.kt the following piece of code:

@kotlin.internal.InlineOnly
public inline fun CharSequence.elementAtOrNull(index: Int): Char? {
    return this.getOrNull(index)
}

What's the reasoning behind using inline here?

JD Hernandez
  • 1,785
  • 1
  • 20
  • 29
mol
  • 2,607
  • 4
  • 21
  • 40

3 Answers3

3

This particular function and a few others in kotlin-stdlib are marked as @InlineOnly so that they are not present in the actual stdlib class files and are only available for the Kotlin compiler to inline them. The goal that is achieved in this way is reducing the methods count in the artifacts, which matters for Android.

Apart from that, using inline functions without lambdas is useful for reifying type parameters.

hotkey
  • 140,743
  • 39
  • 371
  • 326
1

There is still overhead, no matter how minor, that can be avoided.

A similar discussion on Inline Extension Properties.

A post on Kotlin Extensions which gets down into the bytecode effects

dillius
  • 506
  • 4
  • 12
  • In my example the only overhead I see is the extra method declaration. In that case why would I ever want to not mark method with inline? Docs say that inlining large methods results in generated code grow, so should I add inline to every method that is less than let's say 100 lines? – mol Oct 19 '17 at 14:11
  • You can not inline a method which uses backing fields in a class, otherwise go for it. Extension methods don't have this issue because they are technically receiving the class they are extending as an additional parameter, they aren't actually added. – dillius Oct 19 '17 at 14:31
0

I would say that is related to efficiency. Instead of calling functions elementAtOrNull and thus, getOrNull this one is directly called.

Yajairo87
  • 345
  • 1
  • 8
  • 25