Kotlin 科特林游乐场–;变量';mainProperty';初始值设定项是多余的
我正在Kotlin游乐场测试Kotlin 科特林游乐场–;变量';mainProperty';初始值设定项是多余的,kotlin,Kotlin,我正在Kotlin游乐场测试任何类型: fun main() { var mainProperty: Any? = 5.0 mainProperty = "Hello, Kotlin!" println(mainProperty) } 为什么当我为类型为Any的属性指定一个新值时,游乐场会打印结果,但会给我以下消息 // Variable 'mainProperty' initializer is redundant 编译器注
任何类型:
fun main() {
var mainProperty: Any? = 5.0
mainProperty = "Hello, Kotlin!"
println(mainProperty)
}
为什么当我为类型为Any
的属性指定一个新值时,游乐场会打印结果,但会给我以下消息
// Variable 'mainProperty' initializer is redundant
编译器注意到,在重新分配变量之前,您从未使用过5.0值,因此它会警告您这一点
如果在重新分配之间插入打印语句,警告将消失:
fun main() {
var mainProperty: Any? = 5.0
println(mainProperty)
mainProperty = "Hello, Kotlin!"
println(mainProperty)
}
如果您在Intellij这样的IDE上执行此操作并遵循它给出的建议,那么简化后的代码如下:
fun main() {
val mainProperty: Any?
mainProperty = "Hello, Kotlin!"
println(mainProperty)
}
编译器注意到,在重新分配变量之前,您从未使用过5.0值,因此它会对此发出警告
如果在重新分配之间插入打印语句,警告将消失:
fun main() {
var mainProperty: Any? = 5.0
println(mainProperty)
mainProperty = "Hello, Kotlin!"
println(mainProperty)
}
如果您在Intellij这样的IDE上执行此操作并遵循它给出的建议,那么简化后的代码如下:
fun main() {
val mainProperty: Any?
mainProperty = "Hello, Kotlin!"
println(mainProperty)
}
它是多余的,因为你没有访问它就覆盖了它。它是多余的,因为你没有访问它就覆盖了它