Home > Software engineering >  Can I create a map in which some of the keys have no values or are null?
Can I create a map in which some of the keys have no values or are null?

Time:08-12

I want to have a map where some values are blank so that when I loop through the map and run a function I can take advantage of default parameters:

fun main() {
    val users = mapOf("[email protected]" to null, "[email protected]" to "Windows", "[email protected]" to "macOS")

    for (item in users) {
        println(displayAlertMessage(item.value, item.key))
    }
}

fun displayAlertMessage(os: String = "Unknown OS", email: String): String {
    return "There's a new sign-in request on $os for your Google Account $email."
}

I understand there's something weird about using null and it expecting a string, but if I just use "" as the value for the first pair then the function doesn't use the default parameter. Is there a way to do this?

CodePudding user response:

To make your existing code apply the default value for parameter os, you'll have to invoke it without os parameter:

fun main() {
    val users = mapOf("[email protected]" to null, "[email protected]" to "Windows", "[email protected]" to "macOS")

    for (item in users) {
        if (item.value == null)
            println(displayAlertMessage(email = item.key))
        else
            println(displayAlertMessage(item.value!!, item.key))
    }
}

I would probably have done something like this (less code) if only one occurrence of call to displayAlertMessage:

for (item in users) {
    println(displayAlertMessage(item.value ?: "Unknown OS", item.key))
}

Then you can remove default value from displayAlertMessage like this:

fun displayAlertMessage(os: String, email: String): String {
    return "There's a new sign-in request on $os for your Google Account $email."
}
  • Related