Kotlin Kotlin Basics 2 — Questions and Answers
Question 1: Which operator is used to perform a non-null assertion in Kotlin?
- ?.
- ?:
- !! (Correct answer)
- &&
Correct answer: !!
The `!!` operator asserts that a nullable expression is non-null, throwing a NullPointerException if it is null.
Question 2: What is the Elvis operator in Kotlin used for?
- Comparing two values
- Providing a default value when an expression is null (Correct answer)
- Casting a type safely
- Performing bitwise operations
Correct answer: Providing a default value when an expression is null
The Elvis operator `?:` returns the left-hand expression if it is non-null, otherwise it returns the right-hand default value.
Question 3: Which keyword is used to define a constant at the top level in Kotlin?
- final val
- const val (Correct answer)
- static val
- immutable val
Correct answer: const val
`const val` declares a compile-time constant in Kotlin, which must be a primitive type or String at the top level or inside an object.
Question 4: What is string interpolation in Kotlin?
- Concatenating strings with +
- Embedding expressions in strings using $ (Correct answer)
- Converting a number to a string
- Comparing two strings
Correct answer: Embedding expressions in strings using $
Kotlin supports string interpolation using the `$` symbol to embed variables or expressions directly inside string literals.
Question 5: What does `when` replace in Kotlin compared to Java?
- if-else
- switch (Correct answer)
- try-catch
- for loop
Correct answer: switch
Kotlin's `when` expression is a more powerful replacement for Java's `switch` statement, supporting arbitrary conditions.
Question 6: How do you declare a multi-line string in Kotlin?
- Using single quotes ''
- Using triple quotes """ (Correct answer)
- Using backticks ``
- Using the multiline() function
Correct answer: Using triple quotes """
Triple-quoted strings (`"""`) in Kotlin allow multi-line string literals without needing escape characters.
Which operator is used to perform a non-null assertion in Kotlin?