Why is mutableMapOf returning NULL?

I wrote a simple block of code to store fragmentswith idsin Map. Maps valueand keyinitialized as a non-empty, but when I want to get them both key, and valuehe gives the type of data nullable. So I don’t understand why? Is there any other type of card that returns non-nullabledata in Kotlin?

enter image description here

+4
source share
2 answers

It is possible that there is no value for the [position] key that will return null:

abstract operator fun get(key: K): V?

Returns the value corresponding to the given key, or null if such a key is not on the map.

+9
source

@nhaarman , getValue(key), -nullable, NoSuchElementException, .

/**
 * Returns the value for the given [key] or throws an exception if there is no such key in the map.
 *
 * If the map was created by [withDefault], resorts to its `defaultValue` provider function
 * instead of throwing an exception.
 *
 * @throws NoSuchElementException when the map doesn't contain a value for the specified key and
 * no implicit default value was provided for that map.
 */
@SinceKotlin("1.1")
public fun <K, V> Map<K, V>.getValue(key: K): V = getOrImplicitDefault(key)
+3

Source: https://habr.com/ru/post/1683330/


All Articles