Reputation:
According to the official Oracle documentation, the HashMap.getOrDefault(Object Key, V defaultValue)
function can take two arguments, but the compiler reported an error when I run the following program.
fun main(args: Array<String>) {
val numbersMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5
)
println(numbersMap.get("one"))
println(numbersMap["one"])
println(numbersMap.getOrDefault("four", 10))
println(numbersMap["five"])
}
C:\Users\forestfh\Documents\KotlinProjects>kotlinc GetOrDefault.kt
GetOrDefault.kt:11:24: error: unresolved reference. None of the following candid
ates is applicable because of receiver type mismatch:
public inline fun <R, T : String> Result<String>.getOrDefault(defaultValue: Stri
ng): String defined in kotlin
println(numbersMap.getOrDefault("four", 10))
Upvotes: 0
Views: 299
Reputation: 30655
You can use getOrElse()
extension function to retrieve either a stored value or default value:
println(numbersMap.getOrElse("four") { 10 })
Upvotes: 1