Nullability in Kotlin

Null Safety or Nullability 

We have discussed the basic introduction of Kotlin, if you wish to have a look Here you go !!

Kotlin includes nullable types, which can represent the absence of value.  Basically, we can use it to represent the value and absence of that value as well. You might have heard of options in swift. It's the same way. 




var error: Int?


Marking with? This means either it will have the Int or no value. 

error = 100
error = nullvar error: Int?


As you know in swift optional value being wrapped in the optional type so when you try to print the value it will not be like a primitive Int value.  You need to unwrap it the same way we are also going the do the same. 


Not-null assertion operator  (!!) 

which is used to unwrap the value from it.

error !! + 1

Seems it like as in iOS, force unwrapped an optional value with null as the value will make the app crash same way here as well you will get the null-pointer exception 


Smart casts 

Using nullable check you can use to read the value from inside of it.


var authorName:Srtring? = "Kotlin"
var nonNullableName: String

var nullableName: String?

if (authorName != null) {

nonNullableName = authorName

} else {

nullableName = authorName

}


Safe calls 

It's the same as optional chains as in iOS. If you want to access a property of a type. Then use '?'  For safe calls operator.


var nameLength = authorName?.length

// nameLength is of type Int? and not Int, 

Since the result of a safe call can be null, expressions using safe calls on nullable return nullable types. 


 let() func

Same as if let in iOS, using let function calling using Lamba trailing syntax as below.


authorName?.let {

nonNullableName = authorName

}


Elvis operator (?:)

Use to get a value from nullable type. 


var nullableValue: Int? = 10

var hasResult = nullableInt ?: 0

}

Using the Elvis operator means hasResult will equal either the value inside nullableValue, or 0 if nullableValue contains null. 



Wrapping Up:

This is all about the Nullability in Kotlin. Hope you like the article. It's most similar to swift Optional. I have written the optional blog as well if you want to have a look please look at it.

Please share your comment and feedback.  


Stay tuned for the next blog soon on Kotlin.

Happy Coding 😊





Comments

Popular posts from this blog

Introduction to Kotlin