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

霸气de小男生 提交于 2020-11-29 08:27:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/61092285/in-kotlin-whats-the-difference-between-start-and-first

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!