Welcome to your journey into understanding Kotlin's Nullability Annotations! This tutorial is designed to help you navigate through this essential concept, whether you're a beginner or an intermediate learner. Let's dive in!
Before we delve into annotations, let's discuss what nullability means in Kotlin. Nullability refers to whether a reference can hold a null value or not. In Kotlin, variables are non-null by default, which means they cannot hold a null value unless explicitly declared.
To make a variable nullable, we can add a ? after its type. For example:
var name: String?In this case, name can hold a String value or null.
If we want to ensure that a variable cannot be null, we can use the !! operator. However, it's considered unsafe as it throws a NullPointerException if the variable is null. Here's an example:
var name: String = "John"
name!! // this will throw a NullPointerException if name is nullTo ensure safety and prevent NullPointerException, Kotlin provides nullability annotations. These annotations tell the compiler how the variable or function behaves with respect to null values.
?)The ? suffix indicates that a variable or function can return a nullable value. For example:
fun getName(): String? {
// This function can return null
return null
}!)The ! suffix indicates that a variable or function guarantees not to return null. For example:
fun getName(): String {
// This function guarantees not to return null
return "John"
}= null)The = null at the end of a function signature indicates that the function can return null by default, but if not documented, it shouldn't. For example:
fun getName(): String? = null?.) 💡The safe call operator (.?) allows us to safely call a function or access a property on a nullable object without causing a NullPointerException. If the object is null, it returns null.
fun getName(): String? {
// This function can return null
return null
}
val name: String? = getName()
val length = name?.lengthIn the above example, if name is null, length will be null as well, preventing a NullPointerException.
?:) 💡The Elvis operator (?:) provides a default value when a nullable object is null.
val name: String? = getName()
val defaultName = name ?: "Unknown"In this example, if name is null, defaultName will be set to "Unknown".
Let's consider a simple example of a User class with a name property.
class User(var name: String?) {
fun greet() {
println("Hello, $name!")
}
}In the above example, the name property is nullable. Now, if we create a User object and call the greet() function, it might throw a NullPointerException if name is null. To avoid this, we can use the safe call operator:
val user = User(null)
user?.greet() // This won't throw a NullPointerExceptionWhat does the `?` suffix indicate in Kotlin?
That's it for this lesson on Kotlin Nullability Annotations! Stay tuned for more deep dives into Kotlin. Happy coding! 🚀