简体   繁体   中英

Java Integer.MAX_VALUE vs Kotlin Int.MAX_VALUE

I noticed, one interesting thing.
Java's Integer.MAX_VALUE is 0x7fffffff (2147483647)
Kotlin's Int.MAX_VALUE is 2147483647
but if you write
in Java:
int value = 0xFFFFFFFF; //everything is fine (but printed value is '-1')
in Kotlin:
val value: Int = 0xFFFFFFFF //You get exception The integer literal does not conform to the expected type Int

Interesting right? So you're able to do something like new java.awt.Color(0xFFFFFFFF, true) in Java but not in Kotlin.

Color class works with that int on "binary" level, so everything works fine for both platforms with all constructors ( Color(int rgba) or Color(int r, int g, int b, int a) ).
Only workaround which I found for kotlin is java.awt.Color(0xFFFFFFFF.toInt(), true) .

Any idea why is it like this in Kotlin?

This is partially answered here :

In Kotlin you need to prepend the - sign to denote negative Int which is not true in Java.

So it seems that Java will interpret hex literals as signed , whereas Kotlin will treat them as unsigned.

The negation would have to be done manually.

Small aside: JetBrains' Kotlin converter actually converts

int a = 0xffffffff;

to

var a = -0x1

but this may just be it realizing exactly what you have noticed.


The part of the spec for hexadecimal literals doesn't mention this at all, however.

我认为,这个问题应该由Kotlin 1.3UInt来解决,请在此处查看更多信息: https : //kotlinlang.org/docs/reference/whatsnew13.html#unsigned-integers

The explanation is in the reference docs :

Due to different representations, smaller types are not subtypes of bigger ones. If they were, we would have troubles of the following sort:

 // Hypothetical code, does not actually compile: val a: Int? = 1 // A boxed Int (java.lang.Integer) val b: Long? = a // implicit conversion yields a boxed Long (java.lang.Long) print(a == b) // Surprise! This prints "false" as Long's equals() // check for other part to be Long as well

So not only identity, but even equality would have been lost silently all over the place.

As a consequence, smaller types are NOT implicitly converted to bigger types. This means that we cannot assign a value of type Byte to an Int variable without an explicit conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM