0
0
Kotlinprogramming~20 mins

String templates and interpolation in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
String Template Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of simple string template
What is the output of this Kotlin code using string templates?
Kotlin
val name = "Anna"
val age = 25
println("My name is $name and I am $age years old.")
AMy name is Anna and I am 25 years old.
BMy name is $name and I am $age years old.
CMy name is Anna and I am age years old.
DMy name is name and I am 25 years old.
Attempts:
2 left
💡 Hint
Remember that $variable inside a string replaces with the variable's value.
Predict Output
intermediate
2:00remaining
Using expressions inside string templates
What will this Kotlin code print?
Kotlin
val x = 5
val y = 3
println("Sum of $x and $y is ${x + y}")
ASum of 5 and 3 is 53
BSum of x and y is x + y
CSum of 5 and 3 is ${x + y}
DSum of 5 and 3 is 8
Attempts:
2 left
💡 Hint
Expressions inside ${} are evaluated before printing.
🔧 Debug
advanced
2:00remaining
Identify the error in string interpolation
What error does this Kotlin code produce?
Kotlin
val count = 10
println("You have $count items in your cart")
println("Next item price is $price")
ASyntax error: missing curly braces
BNo error, prints both lines correctly
CUnresolved reference: price
DType mismatch error
Attempts:
2 left
💡 Hint
Check if all variables used inside strings are declared.
Predict Output
advanced
2:00remaining
Complex string interpolation with multiline string
What is the output of this Kotlin code?
Kotlin
val user = "Bob"
val score = 42
val message = """
Hello, $user!
Your score is ${score * 2}.
Good luck!
"""
println(message.trim())
A
Hello, $user!
Your score is ${score * 2}.
Good luck!
B
Hello, Bob!
Your score is 84.
Good luck!
C
Hello, Bob!
Your score is score * 2.
Good luck!
DHello, Bob! Your score is 42. Good luck!
Attempts:
2 left
💡 Hint
Multiline strings keep line breaks and expressions inside ${} are evaluated.
🧠 Conceptual
expert
2:00remaining
Understanding string template evaluation order
Consider this Kotlin code snippet: val a = 3 val b = 4 println("Result: ${a + b}") println("Result: $a + $b") What will be the output?
A
Result: 7
Result: 3 + 4
B
Result: 7
Result: 7
C
Result: 7
Result: $a + $b
D
Result: a + b
Result: 3 + 4
Attempts:
2 left
💡 Hint
Expressions inside ${} are evaluated, but $variable just inserts the variable's value.