Recall & Review
beginner
What does the safe call operator
?. do in Kotlin?The safe call operator
?. lets you access a property or call a method on an object only if it is not null. If the object is null, it returns null instead of throwing an error.Click to reveal answer
beginner
How can you provide a default value when accessing a nullable variable in Kotlin?
You can use the Elvis operator
?: to provide a default value if the expression on the left is null. For example: val length = name?.length ?: 0 means if name is null, length will be 0.Click to reveal answer
intermediate
What happens if you use the not-null assertion operator
!! on a null value?Using
!! tells Kotlin you are sure the value is not null. If the value is actually null, the program throws a NullPointerException and crashes.Click to reveal answer
beginner
How do you safely access an element in a list by index in Kotlin?
You can use the
getOrNull(index) function. It returns the element at the given index or null if the index is out of bounds, preventing crashes.Click to reveal answer
beginner
Why is it important to access elements safely in Kotlin?
Accessing elements safely helps avoid program crashes caused by null values or invalid indexes. It makes your code more stable and easier to maintain.
Click to reveal answer
What does
val length = name?.length ?: 0 do if name is null?✗ Incorrect
The Elvis operator
?: provides 0 as a default when name?.length is null.Which operator lets you call a method only if the object is not null?
✗ Incorrect
The safe call operator
?. calls the method only if the object is not null.What does
list.getOrNull(5) return if the list has only 3 elements?✗ Incorrect
getOrNull returns null if the index is out of bounds.What happens if you use
!! on a null variable?✗ Incorrect
The not-null assertion operator
!! throws a NullPointerException if the value is null.Why should you use safe access methods in Kotlin?
✗ Incorrect
Safe access prevents crashes by handling nulls and invalid indexes properly.
Explain how the safe call operator and Elvis operator work together to access nullable elements safely in Kotlin.
Think about how to avoid null pointer errors when accessing properties.
You got /3 concepts.
Describe how to safely get an element from a list by index in Kotlin and why it is important.
Consider what happens if you ask for an element outside the list range.
You got /4 concepts.