Kotlin为什么不执行自动类型转换? [英] Why doesn't Kotlin perform automatic type-casting?
问题描述
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)
为什么Kotlin不执行隐式类型转换并强迫我们传递确切的数据类型?
Why doesn't kotlin perform implicit type conversion and force us to pass the exact type of data?
fun sin(value: Double): Double // at kotlin documentation
推荐答案
我们都知道Kotlin同时具有不可为空的Int
和可为空的Int?
.
We all know that Kotlin has both non-nullable Int
and nullable Int?
.
当我们使用Int?
时,会发生这种情况:Kotlin实际上在Kotlin需要可空引用时将JVM原语装箱",因为它旨在消除代码中空引用的危险.
When we use Int?
this happens: Kotlin actually 'boxes' JVM primitives when Kotlin needs a nullable reference since it's aimed at eliminating the danger of null references from code.
现在看一下:(假设这是一个可编译的代码)
Now look at this: (assuming this is a compilable code)
val a: Int? = 1
val b: Long? = a
Kotlin不会执行隐式类型转换,因为这种情况会发生.如果Kotlin进行了隐式类型转换,则b
应该为1
.但由于a
是装箱的Int
而b
是装箱的Long
,因此 a == b
会产生false
并陷入矛盾,因为其==
运算符会检查equals()
和Long
的equals()
也会检查其他部分是否也是Long
.
Kotlin doesn't perform implicit type conversion because of this thing happens. If Kotlin did implicit type conversions, b
should be 1
. but since a
is a boxed Int
and b
is a boxed Long
, a == b
yields false
and falls into contradiction, since its ==
operator checks for equals()
and Long
's equals()
checks other part to be Long
as well.
查看文档
- 科特林的明确转换
- https://kotlinlang.org/docs/reference/basic-types.html
- https://kotlinlang.org/docs/reference/equality.html
- Explicit Conversions in Kotlin
- https://kotlinlang.org/docs/reference/basic-types.html
- https://kotlinlang.org/docs/reference/equality.html
这篇关于Kotlin为什么不执行自动类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!