我写了一个简单的代码块来存储fragments
与ids
在Map
。地图的value
和key
被初始化为非空值,但是当我想让它们为key
和value
时,它给出nullable
类型的数据。所以,我不明白为什么?有没有其他类型的地图返回数据Kotlin
?为什么mutableMapOf返回空值?
4
A
回答
9
这是可能的存在是关键[位置]没有价值,这将使其返回null
:
abstract operator fun get(key: K): V?
返回对应于给定的密钥,或为空值如果这样的密钥不存在于地图中。
3
@nhaarman是对的,但你可以使用返回非空的getValue(key)
,但如果没有找到则返回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)
相关问题
- 1. 为什么返回空值?
- 2. 为什么SCOPE_IDENTITY()返回空值?
- 3. 为什么document.getElementById返回空值?
- 4. 为什么SSIS查找返回空值?
- 5. 为什么Glass Mapper返回空值?
- 6. 为什么SimpleBeanEditorDriver返回空值
- 7. 为什么它返回空值?(网络)
- 8. 为什么IResource.getRawLocation()返回空值的IProject
- 9. Android/Firebase:为什么onDataChange()返回空值?
- 10. 为什么DLookup返回空?
- 11. 为什么GetAllActorsOfClass返回空?
- 12. 为什么json_decode()返回空?
- 13. 为什么从sqlite返回值返回一个空的数组
- 14. 为什么这个TSql返回一个空值或空值?
- 15. 为什么不为空(0)返回false?
- 16. 为什么(假||空)返回null,而(空||假)返回false?
- 17. quertySelector返回空值是什么?
- 18. 为什么返回空值而不是值?
- 19. 为什么dlsym()返回的符号值为空?
- 20. 当api返回值时,为什么我的JSON解析为空?
- 21. 为什么val()在我的代码中返回的值为空?
- 22. 为什么Web服务返回值为空?
- 23. 为什么github api为语言字段返回空值
- 24. 为什么onActivityResult始终为Intent额外返回空值
- 25. 为什么`mysqli_fetch_assoc`返回空对象?
- 26. 这是为什么返回空白?
- 27. 为什么查询返回空集合?
- 28. 为什么json_encode返回空括号?
- 29. 为什么PHP preg_match返回空?
- 30. 为什么object.getClass()。getClasses()返回空数组?
在你回答之前,我写了这个。 :'''重写fun getItem(position:Int):Fragment =(fragmentsAndIds [position])?:throw NullPointerException()'''' 它确实类似于此。但是你的选择更加简洁。我会用它。谢谢 – emiraslan
是的,它做同样的事情。顺便说一句,你可以写'重写getItem(position:Int):Fragment =(fragmentsAndIds [position])!!'。如果为空,'!!'会抛出'NullPointerException';) –