0
0
Kotlinprogramming~20 mins

Why expressions over statements matters in Kotlin - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Expression Mastery in Kotlin
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using expression style?

Consider this Kotlin code that uses expressions instead of statements. What will it print?

Kotlin
val result = if (5 > 3) "Yes" else "No"
println(result)
A5
BNo
Ctrue
DYes
Attempts:
2 left
💡 Hint

Remember, if in Kotlin can return a value.

🧠 Conceptual
intermediate
1:30remaining
Why prefer expressions over statements in Kotlin?

Which of the following is the best reason to prefer expressions over statements in Kotlin?

AExpressions allow assigning results directly to variables, making code concise and clear.
BExpressions cannot be used inside functions.
CStatements run faster than expressions in Kotlin.
DStatements are required for all control flow in Kotlin.
Attempts:
2 left
💡 Hint

Think about how expressions can produce values.

🔧 Debug
advanced
2:00remaining
What error occurs in this Kotlin code mixing statements and expressions?

Look at this Kotlin code snippet. What error will it cause?

Kotlin
val x: String = if (true) println("Hello") else println("Bye")
println(x)
ANo error, prints Hello and then Hello
BType mismatch: inferred type is Unit but String was expected
CNullPointerException at runtime
DSyntax error: missing else branch
Attempts:
2 left
💡 Hint

Consider what println returns and what if expression expects.

📝 Syntax
advanced
1:30remaining
Which Kotlin code correctly uses expression style for conditional assignment?

Choose the Kotlin code snippet that correctly uses expressions to assign a value based on a condition.

A
val message
if (score > 50) message = "Pass" else message = "Fail"
Bval message = if score > 50 { "Pass" } else { "Fail" }
Cval message = if (score > 50) "Pass" else "Fail"
Dval message = if (score > 50) { "Pass" } else
Attempts:
2 left
💡 Hint

Remember the syntax for if expressions in Kotlin.

🚀 Application
expert
2:00remaining
How many items are in the resulting list after using expression style map?

What is the size of the list result after running this Kotlin code?

Kotlin
val numbers = listOf(1, 2, 3, 4)
val result = numbers.map { if (it % 2 == 0) it * 2 else it }
println(result.size)
A4
B2
C0
DThrows an exception
Attempts:
2 left
💡 Hint

Think about how map transforms each item but keeps the list size.