Java Integer.MAX_VALUE与Kotlin Int.MAX_VALUE

Java Integer.MAX_VALUE vs Kotlin Int.MAX_VALUE

我注意到,一件有趣的事。
Java的Integer.MAX_VALUE0x7fffffff(2147483647)
Kotlin的Int.MAX_VALUE2147483647
但是如果你写
在Java中:
int value = 0xFFFFFFFF;
//everything is fine (but printed value is '-1')

在Kotlin:
val value: Int = 0xFFFFFFFF //You get exception
TheintegerliteraldoesnotconformtotheexpectedtypeInt

有趣吧? 因此,您可以在Java中执行new java.awt.Color(0xFFFFFFFF, true)之类的操作,但在Kotlin中则不能。

Color类在"二进制"级别上与该int一起使用,因此对于具有所有构造函数(Color(int rgba)Color(int r, int g, int b, int a))的两个平台,一切都可以正常工作。
我为kotlin找到的唯一解决方法是java.awt.Color(0xFFFFFFFF.toInt(), true)

知道为什么在Kotlin中会这样吗?


这里部分回答:

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

因此,似乎Java会将十六进制文字解释为带符号,而Kotlin会将其视为无符号。

否定将必须手动完成。

除了一点:JetBrains的Kotlin转换器实际上可以转换

1
int a = 0xffffffff;

1
var a = -0x1

但这可能仅仅是实现了您已经注意到的东西。

但是,十六进制字面值的规范部分完全没有提到这一点。


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


说明在参考文档中:

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

1
2
3
4
5
// 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.