kotlin - 数字类型的自动转换
kotlin - automatic conversion of numeric types
在java中,我们可以将int
赋值给double
,例如double x = 123
;
在 kotlin 中,我们得到一个编译错误。
问:kotlin
可以开启自动转换功能吗?为什么kotlin
默认没有这个功能?
var x: Double = 123; // ERROR
再举一个例子:
fun foo(x: Double) { }
fun main(args: Array<String>) {
foo(123.0); // OK
foo(123); // ERROR
}
更新:
文字123
可以在编译时自动转换为Short
或Long
。但不会转换为Float
或Double
.
fun fooShort(x: Short) {}
fun fooInt(x: Int) {}
fun fooLong(x: Long) {}
fun main(args: Array<String>) {
fooShort(123) // OK
fooInt(123) // OK
fooLong(123) // OK
}
没有。这不会发生。由于 kotlin
是强类型的,这意味着 类型不会被隐式强制转换 。您需要显式类型转换。从 Explicit Conversions 的 Kotlin 参考资料中可以看出:
Due to different representations, smaller types are not subtypes of bigger ones.
[...]
As a consequence, smaller types are NOT implicitly converted to bigger types.
[...]
We can use explicit conversions to widen numbers.
在java中,我们可以将int
赋值给double
,例如double x = 123
;
在 kotlin 中,我们得到一个编译错误。
问:kotlin
可以开启自动转换功能吗?为什么kotlin
默认没有这个功能?
var x: Double = 123; // ERROR
再举一个例子:
fun foo(x: Double) { }
fun main(args: Array<String>) {
foo(123.0); // OK
foo(123); // ERROR
}
更新:
文字123
可以在编译时自动转换为Short
或Long
。但不会转换为Float
或Double
.
fun fooShort(x: Short) {}
fun fooInt(x: Int) {}
fun fooLong(x: Long) {}
fun main(args: Array<String>) {
fooShort(123) // OK
fooInt(123) // OK
fooLong(123) // OK
}
没有。这不会发生。由于 kotlin
是强类型的,这意味着 类型不会被隐式强制转换 。您需要显式类型转换。从 Explicit Conversions 的 Kotlin 参考资料中可以看出:
Due to different representations, smaller types are not subtypes of bigger ones. [...] As a consequence, smaller types are NOT implicitly converted to bigger types. [...] We can use explicit conversions to widen numbers.