Kotlin Kotlin Type System and Null Safety 2 — Questions and Answers
Question 1: Which keyword is used to check if an object is of a specific type in Kotlin?
- instanceof
- typeof
- is (Correct answer)
- checkType
Correct answer: is
The `is` operator checks whether an object is an instance of a given type, similar to Java's `instanceof`.
Question 2: What does the unsafe cast operator `as` do when the object is not of the target type?
- Returns null
- Returns the original object
- Throws ClassCastException (Correct answer)
- Compiles but produces undefined behavior
Correct answer: Throws ClassCastException
The unsafe cast operator `as` throws a `ClassCastException` at runtime if the object cannot be cast to the specified target type.
Question 3: What does the safe cast operator `as?` return when the cast is unsuccessful?
- ClassCastException
- The original object
- An empty instance
- null (Correct answer)
Correct answer: null
The safe cast operator `as?` returns null instead of throwing an exception when the object cannot be cast to the target type.
Question 4: What keyword defines a type alias in Kotlin?
- alias
- typealias (Correct answer)
- typedef
- typeref
Correct answer: typealias
The `typealias` keyword creates an alternative name for an existing type, improving readability for complex type signatures.
Question 5: What is the `Nothing` type in Kotlin primarily used for?
- Representing void functions
- Functions that always throw or loop infinitely (Correct answer)
- Storing null values
- Generic type wildcards
Correct answer: Functions that always throw or loop infinitely
`Nothing` represents a value that never exists; it's the return type of functions like `throw` expressions or infinite loops that never complete normally.
Question 6: After `if (x is String)`, how does Kotlin handle the variable `x` inside the block?
- x must be explicitly cast with `(x as String)`
- x is auto-cast to String via smart casting (Correct answer)
- x remains the original nullable type
- x is widened to Any
Correct answer: x is auto-cast to String via smart casting
Kotlin's smart casting automatically casts `x` to `String` inside the `if (x is String)` block, so no explicit cast is needed.
Question 7: What is `Any` in Kotlin's type system?
- A nullable supertype equivalent to Java's Object
- The supertype of all nullable Kotlin types
- A dynamic type bypassing compile-time checks
- The root supertype of all non-nullable Kotlin types (Correct answer)
Correct answer: The root supertype of all non-nullable Kotlin types
`Any` is the root of Kotlin's class hierarchy and the supertype of all non-nullable types, analogous to Java's `Object` class.
Which keyword is used to check if an object is of a specific type in Kotlin?