menu

Kotlin Basics

Kotlin Basics - Important Points


21.

What is the output of the following code?

fun main() {
val list = listOf(1, 2, 3)
val doubledList = list.map { it * 2 }
println(doubledList)
}

A. [1, 2, 3]

B. [2, 4, 6]

C. [1, 2, 3, 2, 4, 6]

D. This code will not compile.

Discuss Work Space

Answer: option b

Explanation:

The map function is used to transform each element of a collection based on a given transformation function. In this code, the doubledList variable contains the result of doubling each element of the list variable.

22.

What is the output of the following code?

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

A. 0

B. -1

C. null

D. This

Discuss Work Space

Answer: option b

Explanation:

The ?. operator is used for safe navigation in Kotlin, allowing you to access properties or call methods on an object only if it is not null. In this code, the length variable contains the length of the nullableString variable if it is not null, or -1 if it is null.

23.

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)
}

A. [1, 2, 3, 4, 5]

B. [1, 3, 5]

C. [2, 4]

D. This code will not compile.

Discuss Work Space

Answer: option b

Explanation:

The removeIf function is used to remove elements from a collection that match a given predicate function. In this code, the numbers variable contains a list of numbers from 1 to 5, and the removeIf function is used to remove all even numbers from the list.

24.

What is the output of the following code?

fun main() {
val x: Int? = null
val y = 5
println(x ?: y)
}

A. 0

B. 5

C. null

D. This code will not compile.

Discuss Work Space

Answer: option b

Explanation:

The ?: operator is used to provide a default value for nullable variables, similar to the Elvis operator. In this code, the x variable is null, so the y variable is used as the default value.

25.

What is the output of the following code?

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

A. [1, 3, 5]

B. [2, 4]

C. [1, 2, 3, 4, 5]

D. This code will not compile.

Discuss Work Space

Answer: option b

Explanation:

The filter function is used to create a new collection that contains only the elements of the original collection that match a given predicate function. In this code, the filteredNumbers variable contains a list of only the even numbers from the numbers variable.


Subscribe for Latest Career Trends
Subscribe Now
Use AI and ChatGPT for Career Guidance

Unlock Your Future

Join Now
Worried for Placements in 2024?

Join FAST TRACK Course

Join Now
Supercharge Your SUCCESS

Join All in One Placement Mock Tests-2024

Join Now