Sobes.tech
Junior — Middle

How to find an element by key in Kotlin with a message 'Not found' if such element is absent?

sobes.tech AI

Answer from AI

In Kotlin, to find an element by key in a collection (for example, in a Map), you can use the access operator by key map[key]. If the element is missing, it returns null. To display the message "Not found" if the element is not found, you can use the Elvis operator ?:.

Example:

val map = mapOf("key1" to "value1", "key2" to "value2")

val keyToFind = "key3"
val result = map[keyToFind] ?: "Not found"
println(result) // Will output: Not found

If the collection is a list of objects, and you need to search by some field, you can use the find function:

data class Item(val id: Int, val name: String)

val list = listOf(Item(1, "A"), Item(2, "B"))

val item = list.find { it.id == 3 } ?: run {
    println("Not found")
    null
}

Thus, if the element is not found, the message "Not found" is displayed.