Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

int - Are Kotlin data types built off primitive or non-primitive Java data types?

I am new to Kotlin and was playing around with the data types. I took an Int type and then tried to cast it as a Double by saying num as Double, a call that is valid in java (non syntactically but you get the point). However, this failed, saying that Int cannot be cast to Double. I am assuming this is because it is built off the Integer class rather than the raw int data type. Am I correct, and what is the most efficient way to cast values? There is a .toDouble() function, but this seems inefficient and unwieldy.

question from:https://stackoverflow.com/questions/45420806/are-kotlin-data-types-built-off-primitive-or-non-primitive-java-data-types

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I took an Int type and then tried to cast it as a Double by saying num as Double <...> However, this failed, saying that Int cannot be cast to Double. I am assuming this is because it is built off the Integer class rather than the raw int data type.

No, and there are two important points to note:

  • Kotlin positions its numeric types (Int, Long, Double etc.) as not being nested into each other, there is no subtyping relationship between these types. That's why the cast intNum as Double does not succeed in Kotlin. That's also why there's no implicit conversions between these types. Instead, the numeric conversion is done with the corresponding functions (e.g. .toDouble())

  • The numeric type usages in Kotlin are compiled into JVM primitives where possible. Some usages require boxed types (e.g. a nullable Int? requires boxing, and so does a generic type implementation with an Int as a type argument), but the compiler decides whether they are necessary for each case.

<...> What is the most efficient way to cast values? There is a .toDouble() function, but this seems inefficient and unwieldy.

The most efficient way is to use the numeric conversion functions like .toDouble(). In fact, these functions are intrinsified, and there is no function call overhead when you use them. They are compiled closely to what javac would produce for a Java numeric cast or an implicit conversion. You can inspect the bytecode that the Kotlin compiler produces to find out what it's under the hood and whether a specific conversion introduces any overhead.

See also: an answer to a similar question, (link)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...