为什么Kotlin不进行自动型铸造?

Jav*_*ana 5 casting kotlin

var a : Double
a = Math.sin(10) // error: the integer literal does not conform to the expected type Double
a = Math.sin(10.0) //This compiles successfully
println(a)
Run Code Online (Sandbox Code Playgroud)

为什么kotlin不执行隐式类型转换并迫使我们传递确切类型的数据?

fun sin(value: Double): Double // at kotlin documentation
Run Code Online (Sandbox Code Playgroud)

shi*_*psh 6

我们都知道Kotlin既不可空Int也可以为空Int?.

当我们使用Int?这种情况时:当Kotlin需要一个可以为空的引用时,Kotlin实际上"装箱"JVM原语,因为它旨在消除代码中空引用的危险.

现在看看这个:(假设这是一个可编译的代码)

val a: Int? = 1
val b: Long? = a
Run Code Online (Sandbox Code Playgroud)

由于这件事发生,Kotlin不执行隐式类型转换.如果Kotlin做了隐式类型转换,b应该是1.但由于a是装箱Intb是一个装箱Long,a == b产率false并落入矛盾的,因为其==对操作者检查equals()Longequals()检查其他部分是Long为好.

查看文档: