0
0
Kotlinprogramming~20 mins

Named arguments for clarity in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Named Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of function call with named arguments
What is the output of this Kotlin code using named arguments?
Kotlin
fun greet(name: String, greeting: String = "Hello") {
    println("$greeting, $name!")
}

greet(greeting = "Hi", name = "Anna")
AHi, Anna!
BHello, Anna!
CHi, greeting!
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the arguments are passed by name, not by position.
Predict Output
intermediate
2:00remaining
Output with default and named arguments
What will this Kotlin code print?
Kotlin
fun calculate(x: Int, y: Int = 10, z: Int = 5) = x + y * z

println(calculate(z = 3, x = 2))
ACompilation error
B17
C32
D15
Attempts:
2 left
💡 Hint
Remember the order of operations and which arguments are used.
🔧 Debug
advanced
2:00remaining
Identify the error with named arguments
What error does this Kotlin code produce?
Kotlin
fun displayInfo(name: String, age: Int) {
    println("Name: $name, Age: $age")
}

displayInfo(age = 25)
AError: No value passed for parameter 'name'
BCompilation succeeds with no output
CPrints: Name: , Age: 25
DError: Named argument 'age' not found
Attempts:
2 left
💡 Hint
Check if all required parameters have values.
📝 Syntax
advanced
2:00remaining
Which call is syntactically correct?
Given the function below, which call is syntactically correct in Kotlin?
Kotlin
fun orderPizza(size: String, cheese: Boolean = true, pepperoni: Boolean = false) {}

// Calls:
AorderPizza(size = "Medium", pepperoni = true)
BorderPizza(cheese = false, "Large")
CorderPizza("Small", pepperoni = true, cheese = false)
DorderPizza(pepperoni = true, cheese = false, "Large")
Attempts:
2 left
💡 Hint
Named arguments must come after positional arguments.
🚀 Application
expert
3:00remaining
Determine the final map after function calls with named arguments
Consider this Kotlin function that updates a map. What is the final content of the map after these calls?
Kotlin
fun updateMap(map: MutableMap<String, Int>, key: String, value: Int = 1) {
    map[key] = map.getOrDefault(key, 0) + value
}

val myMap = mutableMapOf("a" to 2)
updateMap(map = myMap, key = "b")
updateMap(key = "a", map = myMap, value = 3)
updateMap(myMap, "b", 4)

println(myMap)
A{a=2, b=8}
B{a=3, b=5}
C{a=5, b=1}
D{a=5, b=5}
Attempts:
2 left
💡 Hint
Trace each call and how the map updates with default and named arguments.