menu

Kotlin Basics


1. What is the difference between a primary constructor and a secondary constructor in Kotlin?

A primary constructor is called before any secondary constructors, while a secondary constructor is called before the primary constructor.

A primary constructor is defined inside the class definition, while a secondary constructor is defined outside the class definition.

A primary constructor takes parameters that are used to initialize properties, while a secondary constructor can have additional logic or functionality.

There is no difference between a primary and a secondary constructor in Kotlin.


2.

What is the output of the following code?

fun main() {
val numbers = mutableListOf(1, 2, 3, 4, 5)
numbers.removeIf { it % 2 == 0 }
println(numbers)
}

[1, 2, 3, 4, 5]

[1, 3, 5]

[2, 4]

This code will not compile.


3. Which of the following is true about variables in Kotlin?

They must be explicitly declared with a type.

They can be implicitly declared without a type.

They cannot be reassigned once initialized.

They are always mutable.


4. Which of the following is a valid identifier in Kotlin?

var

my-variable

123foo

MyClass


5. What is the Elvis operator in Kotlin?

A type of operator used for bitwise operations.

A type of operator used for arithmetic operations.

A type of operator used for null safety.

A type of operator used for logical operations.


6.

What is the output of the following code?

fun main() {
val nullableString: String? = null
val length = nullableString?.length ?: -1
println(length)
}

0

-1

null

This


7. What is the syntax for a lambda expression in Kotlin?

{x, y -> x + y}

(x, y) => x + y

[x, y] -> x + y

(x, y) -> {x + y}


8. What is the difference between a range and an array in Kotlin?

A range is a collection of values between two endpoints, while an array is a fixed-size collection of elements.

A range is a fixed-size collection of elements, while an array is a variable-size collection of elements.

There is no difference between a range and an array in Kotlin.

A range and an array are both used to store collections of values.


9. What is the difference between "val" and "var" in Kotlin?

val is used for variables that can be changed, while "var" is used for variables that are constant.

val is used for variables that are constant, while "var" is used for variables that can be changed.

val and "var" are interchangeable and can be used interchangeably.

val and "var" are not supported in Kotlin.


10. Which of the following is an example of inheritance in Kotlin?

class MyClass {}

interface MyInterface {}

class MySubclass : MyClass {}

All of the above