AAD AAD Kotlin & Programming Fundamentals 1 — Questions and Answers
Question 1: Which Kotlin keyword is used to declare a read-only variable that cannot be reassigned after initialization?
- var
- const
- val (Correct answer)
- final
Correct answer: val
The val keyword declares a read-only (immutable reference) variable in Kotlin that cannot be reassigned, similar to final in Java.
Question 2: What is a lambda expression in Kotlin?
- A type of class declaration
- An anonymous function that can be stored in a variable and passed as an argument (Correct answer)
- A keyword for null safety
- A coroutine builder
Correct answer: An anonymous function that can be stored in a variable and passed as an argument
A lambda in Kotlin is an anonymous function defined with curly braces {} that can be passed as an argument or stored in a variable.
Question 3: What does the Elvis operator (?:) do in Kotlin?
- Performs a null-safe function call
- Casts a type safely
- Returns the left-hand expression if non-null, otherwise returns the right-hand expression (Correct answer)
- Throws an exception if null
Correct answer: Returns the left-hand expression if non-null, otherwise returns the right-hand expression
The Elvis operator ?: returns the left-hand value if it is non-null; otherwise, it returns the right-hand fallback value.
Question 4: What is a data class in Kotlin primarily used for?
- Defining singleton objects
- Holding data with auto-generated equals(), hashCode(), toString(), and copy() methods (Correct answer)
- Managing background coroutines
- Declaring abstract interfaces
Correct answer: Holding data with auto-generated equals(), hashCode(), toString(), and copy() methods
A Kotlin data class automatically generates equals(), hashCode(), toString(), copy(), and componentN() functions based on the constructor properties.
Question 5: What does the safe-call operator (?.) do in Kotlin?
- Throws a NullPointerException if the object is null
- Casts the object to a non-null type
- Calls the method only if the object is non-null, otherwise returns null (Correct answer)
- Forces the compiler to ignore null checks
Correct answer: Calls the method only if the object is non-null, otherwise returns null
The safe-call operator ?. invokes a property or method only if the receiver is non-null; if it is null, the entire expression evaluates to null.
Question 6: What is a coroutine in Kotlin?
- A type of Kotlin class
- A lightweight concurrency primitive that can be suspended and resumed without blocking a thread (Correct answer)
- A background Service component
- A design pattern for inheritance
Correct answer: A lightweight concurrency primitive that can be suspended and resumed without blocking a thread
A Kotlin coroutine is a concurrency design pattern that allows you to write asynchronous, non-blocking code in a sequential style using suspend functions.
Which Kotlin keyword is used to declare a read-only variable that cannot be reassigned after initialization?