Kotlin Kotlin Basics and Syntax 2 — Questions and Answers
Question 1: How do you write a single-expression function in Kotlin?
- fun add(a: Int, b: Int) { return a + b }
- fun add(a: Int, b: Int) = a + b (Correct answer)
- fun add(a: Int, b: Int) -> a + b
- def add(a: Int, b: Int) = a + b
Correct answer: fun add(a: Int, b: Int) = a + b
Kotlin allows single-expression functions using the `=` syntax, omitting the curly braces and `return` keyword.
Question 2: What is the output of `'A'.code` in Kotlin?
- A
- 65 (Correct answer)
- 1
- Char
Correct answer: 65
The `.code` property on a `Char` returns its Unicode code point as an `Int`; for 'A' that is 65.
Question 3: Which of the following correctly uses string interpolation in Kotlin?
- "Hello " + name
- "Hello ${name}" (Correct answer)
- "Hello #name"
- f"Hello {name}"
Correct answer: "Hello ${name}"
Kotlin uses `${}` for string interpolation, embedding expressions directly inside string literals.
Question 4: What does `!!` do in Kotlin?
- Safe call on nullable
- Non-null assertion that throws NullPointerException if null (Correct answer)
- Double negation operator
- Checks if a value is not null
Correct answer: Non-null assertion that throws NullPointerException if null
The `!!` operator asserts that the value is non-null and throws `KotlinNullPointerException` if the value is null.
Question 5: What is the range of the Kotlin `Byte` type?
- -128 to 127 (Correct answer)
- 0 to 255
- -256 to 255
- -32768 to 32767
Correct answer: -128 to 127
Kotlin's `Byte` type is a signed 8-bit integer with a range of -128 to 127.
Question 6: Which Kotlin keyword is equivalent to Java's `instanceof`?
- typeof
- is (Correct answer)
- as
- instanceof
Correct answer: is
Kotlin uses `is` to check whether an object is an instance of a particular type, similar to Java's `instanceof`.
How do you write a single-expression function in Kotlin?