gpt4 book ai didi

type-conversion - kotlin - 数字类型的自动转换

转载 作者:行者123 更新时间:2023-12-04 07:20:45 25 4
gpt4 key购买 nike

在java中,我们可以分配 intdouble ,例如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可以自动转换为ShortLong在编译时。但不会转换为 FloatDouble .

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 是强类型的,这意味着类型不会被隐式强制。您需要显式类型转换。来自 Kotlin 引用 Explicit number conversions据称:

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.

关于type-conversion - kotlin - 数字类型的自动转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44124825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com