kotlin Null Safety code example

Example 1: !! in kotlin

//The not-null assertion operator
val l = b!!.length

Example 2: elvis operator kotlin example

val l = b?.length ?: -1

Example 3: kotlin Null Safety

// 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

Example 4: null check in kotlin

if(a != null)  {
//do something
}

Tags:

Misc Example