The !! Sure operator

The not null assertion operator, also known as the sure operator, is used when it is sure that the provided variable always contains a value and is not null. Let's take a look at an example of how this works. Create a nullable string variable and assign a null value to it. Now try get the string's length with the null assertion operator:

fun main(args: Array<String>) {
var sureNotNull : String? = null
var length = sureNotNull!!.length // application will be crashed
println("value of length is " + length)
}

Of course, the application will crash. In this case, the programmer takes responsibility for variable nullability. Let's elaborate on this further with the another example.

The string class provides the lastOrNull function. This function returns the last character of the string, or null if the string is empty. We must declare a nullable character for assigning a value from the lastOrNull function:

val ch : Char? = "abc".lastOrNull()

If we try to declare a normal variable instead of nullable, Kotlin will throw a compile time error. See the following example:

val ch : Char = "abc".lastOrNull()
// Type mismatch: inferred type is Char? but Char was expected

If we are confident that an object (the "abc" string, in this case) is not null and we don't want to create a nullable variable with the null safety operator, we can use the null assertion operator:

val ch : Char = "abc".lastOrNull()!!

See the following example to verify how variables can be declared with and without the null safety operator:

fun mayBeNull(s : String ) : Char? {
val ch: Char? = s.lastOrNull()
return ch
}

fun notNull(s : String ) : Char{
val ch = s.lastOrNull()!!
return ch
}

fun main(args: Array<String>) {
var ch = notNull("abc")
// var ch = notNull("") program will crash.
println(ch)
}

The myBeNull function takes a string as a parameter and returns the last character of the string using the lastOrNull function. Notice that the function returns a nullable Char because  function may receive an empty string as a parameter. On the other hand, the notNull function returns a normal character because this function uses the not null assertion operator to get the last character of the string, and we tell the compiler that this function will never receive an empty string.  

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.77.208