代码之家  ›  专栏  ›  技术社区  ›  Andy Jazz

Kotlin游乐场变量“mainProperty”初始值设定项是多余的

  •  -1
  • Andy Jazz  · 技术社区  · 5 年前

    我在测试 Any 在Kotlin游乐场输入:

    fun main() {
        
        var mainProperty: Any? = 5.0
        
        mainProperty = "Hello, Kotlin!"
    
        println(mainProperty)
    }
    

    为什么要将新值赋给类型的属性 任何 ,游乐场打印结果,但给我以下信息?

    // Variable 'mainProperty' initializer is redundant
    

    enter image description here

    1 回复  |  直到 5 年前
        1
  •  1
  •   Ricardo Ebbers    5 年前

    你从来没有注意到编译器 5

    如果在重新分配之间插入打印语句,则警告将消失:

    fun main() {
        
        var mainProperty: Any? = 5.0
        
        println(mainProperty)
        
        mainProperty = "Hello, Kotlin!"
    
        println(mainProperty)
    }
    

    fun main() {
    
        val mainProperty: Any?
    
        mainProperty = "Hello, Kotlin!"
    
        println(mainProperty)
    }