Kotlin requireNotNull and checkNotNull: Safe Calls in Kotlin 🎯

beginner
8 min

Kotlin requireNotNull and checkNotNull: Safe Calls in Kotlin 🎯

Welcome to this comprehensive tutorial on Kotlin's requireNotNull and checkNotNull! These powerful functions are part of Kotlin's Null Safety features, making your code safer and less prone to errors. Let's dive in!

Understanding Nulls 📝

Before we delve into requireNotNull and checkNotNull, let's understand what nulls are in Kotlin. A null is a special value representing the absence of an object. It's important to handle nulls carefully because they can lead to NullPointerException if not handled properly.

Introduction to Safe Calls 💡

Safe Calls are a way to avoid NullPointerException by providing a default value when a null is encountered. Kotlin provides two safe call functions: requireNotNull and checkNotNull.

requireNotNull 💡

requireNotNull is a function provided by Kotlin to ensure that a value is not null. If the value is null, it throws a NullPointerException. Here's an example:

kotlin
class User(val name: String) fun main() { val user: User? = null user?.let { println(it.name) } // This will not print anything because user is null }

In the above example, we have a User class with a non-null name property. We declare a variable user of type User?, which means it can hold a null value. We then try to print the name property using the let function along with the ?. (safe call) operator. If user is not null, it prints the name. If it is null, nothing happens because the safe call operator returns null and the let function doesn't execute the block.

To make sure that user is not null, we can use requireNotNull:

kotlin
class User(val name: String) fun main() { val user: User? = null user?.requireNotNull()?.let { println(it.name) } // This will throw a NullPointerException }

In this example, requireNotNull checks if user is null. If it is, it throws a NullPointerException. If it's not null, the let function is executed, and the name is printed.

checkNotNull 💡

checkNotNull is another safe call function that allows you to provide a default value when a value is null. Here's an example:

kotlin
class User(val name: String) fun main() { val user: User? = null val userName = user?.let { it.name } ?: "Anonymous" println(userName) // This will print "Anonymous" }

In this example, we use the ?: operator to provide a default value ("Anonymous") when user is null. If user is not null, we print its name.

Quiz 📝

Quick Quiz
Question 1 of 1

What will be printed in the `main` function of the above example if `user` is null?

That's it for this tutorial! You now understand the basics of Kotlin's requireNotNull and checkNotNull functions. Keep practicing, and you'll be a Kotlin pro in no time! 🚀

Stay tuned for more tutorials on Kotlin and other programming languages here at CodeYourCraft! 😉