Welcome to our Kotlin Not-Null Assertion (!!) tutorial! In this comprehensive guide, we'll dive into one of Kotlin's powerful safety features that helps prevent NullPointerExceptions. By the end, you'll be equipped to use not-null assertions in your projects with confidence. 🎯
Not-null assertion is a way to express that you, the developer, know a variable won't be null at a particular point in the code. It's like a safety net to ensure that your program won't crash due to null pointer exceptions. 💡
The syntax for a not-null assertion is simple: !!. Let's see it in action:
var myString: String? = null
if (myString != null) {
val safeString = myString!! // Not-null assertion
println(safeString.length)
} else {
println("myString is null")
}In the above example, we have a nullable string myString. We're using an if statement to check if myString is not null, and if it's not, we're using a not-null assertion to safely access its length property. 📝
What does the `!!` operator do in Kotlin?
String?, Int?) to make your intent clear and make not-null assertions more meaningful.let or ifNull provided by Kotlin standard library.Let's consider a simple example of fetching data from a server and processing it.
class DataFetcher {
fun fetchUser(userId: Int?, callback: (User?) -> Unit) {
// Pretend we're fetching user data from a server
Thread.sleep(2000)
if (userId != null) {
val user = User(userId)
callback(user)
} else {
callback(null)
}
}
}
class User(val id: Int)
fun main() {
val dataFetcher = DataFetcher()
dataFetcher.fetchUser(1) { user ->
if (user != null) {
println("User fetched: ${user.id}")
} else {
println("Error fetching user")
}
}
dataFetcher.fetchUser(null) { user ->
if (user == null) {
println("Expected null, everything is fine.")
} else {
println("Received non-null user when expecting null.")
}
}
}In this example, we're using a DataFetcher class to fetch a user from a server. We're using not-null assertions to ensure that we're processing the user data correctly. ✅
And that's a wrap! You now have a solid understanding of Kotlin's not-null assertion. Happy coding! 🚀