0
0
Kotlinprogramming~5 mins

Null safety in collections in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does null safety mean in Kotlin collections?
Null safety means Kotlin collections can be designed to either allow or disallow null values, helping prevent errors caused by unexpected nulls.
Click to reveal answer
beginner
How do you declare a list that cannot contain null values in Kotlin?
Use List<Type> without a question mark. For example, val list: List<String> means no nulls allowed in the list.
Click to reveal answer
beginner
How do you declare a list that can contain null values in Kotlin?
Use a nullable type inside the list, like List<String?>. This means the list can hold strings or nulls.
Click to reveal answer
intermediate
What happens if you try to add a null to a non-nullable collection in Kotlin?
The code will not compile because Kotlin enforces null safety at compile time, preventing nulls in non-nullable collections.
Click to reveal answer
intermediate
Explain the difference between MutableList<String> and MutableList<String?>.
MutableList<String> can only hold non-null strings, while MutableList<String?> can hold strings and null values.
Click to reveal answer
Which Kotlin collection declaration allows null values inside the collection?
AMutableList<String>
BList<String>
CList<String?>
DSet<String>
What will happen if you try to add null to a MutableList<String>?
ACompile-time error
BNull is added successfully
CRuntime exception
DThe list ignores the null
How do you declare a map in Kotlin that can have null values but non-null keys?
AMap<String, String>
BMap<String?, String>
CMap<String?, String?>
DMap<String, String?>
Which of these is a nullable collection type in Kotlin?
AList<String?>
BList<String>
CMutableList<Int>
DSet<Double>
Why is null safety important in Kotlin collections?
ATo allow any type of data
BTo avoid null pointer exceptions
CTo make collections slower
DTo allow duplicates
Describe how Kotlin handles null safety in collections and why it is useful.
Think about how Kotlin uses question marks to allow or disallow nulls.
You got /3 concepts.
    Explain the difference between List<String> and List<String?> in Kotlin.
    Focus on the question mark after the type inside the list.
    You got /3 concepts.