Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin, what's the difference between start and first?

Tags:

range

kotlin

I'm learning Kotlin, but I can't seem to find straight answers to simple questions. I presume that it's so new, no one has had a chance to ask the obvious questions yet. So here it goes.

When I want to get the smallest item in a range, I type:

range.start

But I get the warning, "Could be replaced with unboxed first". Not sure what unboxed means--can't even guess. But when I use this command:

range.first

the warning goes away. What's happening here? Should I even be concerned? Why does Kotlin have both a start and a first?

like image 389
SMBiggs Avatar asked Dec 22 '22 18:12

SMBiggs


1 Answers

Boxing and unboxing refers to wrapping a primitive value in a class so it can be used with generic classes and functions or as a nullable. In Java, this is more transparent because the primitive and boxed versions of each type of variable have different names (i.e. int and Integer), whereas in Kotlin this is not very obvious. If your variable is nullable, like Int?, it is always boxed, but if it's non-nullable, it's only boxed if it's passed to a function that's generic or requests a nullable version. So boxing as a verb refers to the variable getting wrapped in a class at the moment it is passed to something that requires a boxed version.

There is an interface for a generic range called ClosedRange. When you are working with integer ranges, you are using a class called IntRange that also implements ClosedRange<Int>.

When you use the properties of the generic interface like start, the JVM has to box and unbox your Int value. This is because generics cannot be used with non-boxed primitives. There is a small amount of runtime overhead to box and unbox the primitive.

The actual class IntRange stores the values for the start and end of the range as primitives, so if you access them directly with first, you bypass the boxing that occurs if you go through the generic interface property, for a small performance gain.

In the vast majority of cases, the performance difference will be negligible anyway, but the default code inspection recommends you to use the more performant way.

like image 158
Tenfour04 Avatar answered Jan 12 '23 19:01

Tenfour04