Kotlin Kotlin Type System and Null Safety 1 — Questions and Answers
Question 1: What symbol is appended to a type to make it nullable in Kotlin?
- !
- ? (Correct answer)
- *
- ~
Correct answer: ?
In Kotlin, appending `?` to a type name makes it nullable, allowing the variable to hold null values.
Question 2: What does the safe call operator `?.` return when the receiver is null?
- Throws NullPointerException
- Returns the default value
- null (Correct answer)
- An empty object
Correct answer: null
The safe call operator `?.` returns null instead of throwing an exception when the receiver is null.
Question 3: Which operator in Kotlin throws KotlinNullPointerException if the value is null?
- ?.
- ?:
- as?
- !! (Correct answer)
Correct answer: !!
The `!!` non-null assertion operator converts a nullable type to non-nullable and throws KotlinNullPointerException if the value is null.
Question 4: What is the Elvis operator `?:` used for in Kotlin?
- Performing safe casts
- Type checking at runtime
- Providing a default value when an expression is null (Correct answer)
- Declaring nullable types
Correct answer: Providing a default value when an expression is null
The Elvis operator `?:` returns the left-hand value if it's not null, or the right-hand value as a fallback when it is null.
Question 5: After a null check `if (x != null)`, Kotlin automatically treats `x` as non-nullable inside the block. This is called:
- Auto-boxing
- Type inference
- Type promotion
- Smart casting (Correct answer)
Correct answer: Smart casting
Smart casting is when Kotlin automatically casts a variable to a non-nullable type after the compiler verifies through a null check that it cannot be null.
Question 6: What is the result of `val x: String? = null; val len = x?.length ?: -1`?
- NullPointerException
- -1 (Correct answer)
- 0
- null
Correct answer: -1
`x?.length` returns null because `x` is null, and the Elvis operator `?:` then returns -1 as the fallback value.
Question 7: Which of the following will cause a compilation error in Kotlin when `x` is of type `String?`?
- x?.doSomething()
- x ?: defaultValue
- if (x != null) x.doSomething()
- x.doSomething() (Correct answer)
Correct answer: x.doSomething()
Calling `x.doSomething()` directly on a nullable type without null handling causes a compilation error; Kotlin enforces null safety at compile time.
What symbol is appended to a type to make it nullable in Kotlin?