kotlinbeginner
Kotlin Basics
Variables, null safety and functions
6 questions
By EZ4Code Team
1. What are the keywords for declaring immutable and mutable variables in Kotlin?
val immutable, var mutable
const immutable, var mutable
val mutable, let immutable
final immutable, var mutable
Explanation: val (read-only reference; the reference is immutable but the object's contents may be mutable); var (mutable reference). Prefer val.
2. How does Kotlin's null safety manifest?
Types are non-null by default; nullable types must explicitly use ?
All types can be null
null is not supported
null is only checked at runtime
Explanation: Kotlin's type system distinguishes nullable from non-null: String is non-null and cannot be assigned null; String? is nullable. The compiler prevents unsafe null operations.
3. What does the safe call operator ?. do?
If the object is non-null, calls the method; otherwise returns null
Force-unwraps and crashes when null
Declares a nullable type
Type conversion
Explanation: obj?.method() calls method and returns the result when obj is non-null; when obj is null, the whole expression returns null, enabling safe chained calls.
4. What does the Elvis operator ?: do?
Returns the right-side default value when the left side is null
Crashes when the left side is null
Type checking
Bitwise operation
Explanation: a ?: b returns a when a is non-null, otherwise returns b; commonly used to provide default values, e.g. val name = input ?: "unknown".
5. What is the syntax for declaring a Kotlin function?
fun add(a: Int, b: Int): Int {
return a + b
}fun add(a: Int, b: Int): Int
function add(a, b): Int
def add(a: Int, b: Int): Int
Int add(Int a, Int b)
Explanation: Kotlin uses the fun keyword to declare functions; parameters use the format name: Type, and the return type comes after the parameter list, e.g. fun add(a: Int, b: Int): Int.
6. What is the Kotlin when expression equivalent to in other languages?
switch, but more powerful and can be used as an expression that returns a value
if-else
for loop
try-catch
Explanation: when is an enhanced switch that supports arbitrary conditions, type checks, and range matching, and is an expression that can return a value; it must be exhaustive (or use else).