Kotlin是否具有原始类型? [英] Does Kotlin have primitive types?

查看:140
本文介绍了Kotlin是否具有原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

科特林有原始类型吗?当我声明变量:val myAge: Int = 18时,myAge变量将实际值存储为18还是将对象的地址存储在内存中?如果Int是原始类型,那么为什么我们可以使用myAge.minus(10)这样的方法呢?

Does Kotlin have primitive types?. When I declare the variable: val myAge: Int = 18 then the myAge variable stores the actual values is 18 or stores the addresses of the objects in the memory?. If Int is primitive type then why we can use its method like myAge.minus(10)?

推荐答案

否...是.

Kotlin没有原始类型(我的意思是您不能直接声明原始).它使用IntFloat之类的类作为基元的对象包装.

Kotlin doesn't have primitive type (I mean you cannot declare primitive directly). It uses classes like Int, Float as an object wrapper for primitives.

当将kotlin代码转换为jvm代码时,只要有可能,原始对象"就会被删除.转换为Java原语. 在某些情况下,这无法完成.这些情况是例如原语"的集合.例如,List<Int>不能包含原语.因此,编译器知道何时可以将对象转换为原始类型.而且,它与java非常相似:

When kotlin code is converted to jvm code, whenever possible, "primitive object" is converted to java primitive. In some cases this cannot be done. Those cases are, for example, collection of "primitives". For example, List<Int> cannot contains primitive. So, compiler knows when it can convert object to primitive. And, again, it's very similar to java:

List<Integer> numbers = new ArrayList<>;

numbers.add(0); // <-- you use primitive, but in fact, JVM will convert this primitive to object.
numbers.add(new Integer(0)); // <-- We don't need do that.

此外,当您声明可空基元"时,它永远不会转换为原始值(这很明显,因为原始值不能为null).在Java中,它的工作原理非常相似:

Also, when you declare "nullable primitive" it is never converted to primitive (what is kind of obvious, as primitive cannot be null). In java it works very similar:

int k = null; // No way!
Integer kN = null; // That's OK.

还有一件事-文档对此有何评论?

One more thing - what docs are saying about it?

对于Common,JVM,JS

For Common, JVM, JS

代表32位有符号整数.在JVM上,此类型的非空值表示为原始类型int的值.

Represents a 32-bit signed integer. On the JVM, non-nullable values of this type are represented as values of the primitive type int.

对于本地人

代表32位带符号整数.

Represents a 32-bit signed integer.

@see: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html

最后一个结论. Kotlin没有开箱即用的原始类型.您将所有对象都视为对象.转换为原语比代码要低一些.造成这种设计是为了保持与JVM的兼容性.

So, the last conclusion. Kotlin doesn't have primitive types out of the box. You treat all objects like objects. Converting to primitive is done at some lower level than code. This design is caused to keep compatibility with JVM.

我做了一些深入的探讨,并在媒体上发表了它.有兴趣的人士: https://medium.com/@przemek.materna/kotlin-is-not-primitive-primitives-in-kotlin-and-java-f35713fda5cd

I did a little deep dive and published it on medium. For interested: https://medium.com/@przemek.materna/kotlin-is-not-primitive-primitives-in-kotlin-and-java-f35713fda5cd

这篇关于Kotlin是否具有原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆