📜  kotlin Null 安全性 - Kotlin 代码示例

📅  最后修改于: 2022-03-11 14:53:31.788000             🧑  作者: Mango

代码示例2
// Variable types in Kotlin don't allow the assignment of null. 
// Declare a nullable varible by adding ? at the end of its type.
var neverNull: String = "This can't be null"            
neverNull = null                                        // Error
var nullable: String? = "You can keep a null here"      
nullable = null                                         // Ok
var inferredNonNull = "The compiler assumes non-null"   
inferredNonNull = null                                  // Error
fun strLength(notNull: String): Int {                   
    return notNull.length
}
strLength(neverNull)                                    // Ok
strLength(nullable)                                     // Error