![](/img/trans.png)
[英]Having a getter return a non-nullable type even though the backing field is nullable
[英]Return non-nullable type
我敢肯定,我的代码返回的不是 null 值:
fun getBitmap(id: Int): Bitmap{
if (!(id in bitmapStorage))
bitmapStorage.put(id, BitmapFactory.decodeResource(resources, id))
return bitmapStorage.get(id)
}
返回Bitmap
类型而不是Bitmap?
?
!!
, as Bitmap
或其他?
你可以使用!!
运算符或 MutableMap 的 API - getOrPut
,它将返回非空类型
fun getBitmap(id: Int): Bitmap{
return bitmapStorage.getOrPut(id) {BitmapFactory.decodeResource(resources, id)}
}
请注意,如果同时修改 map,则不能保证该操作是原子的。
鉴于您在bitmapStorage
上执行的操作,我假设它是MutableMap
的一个实例。 如果是这样的话,我认为有一种更惯用的方法可以达到相同的结果,它涉及使用getOrPut
方法。 基本上,它返回与给定键关联的值(如果存在),否则它将您想要的任何值关联到给定键并返回该值。
例子:
val myMap = mutableMapOf<String, String>(
"key1" to "value1"
)
fun complexMethodToComputeValue(): String {
// do something complex
return "I will be called"
}
val value1 = myMap.getOrPut("key1") {
// this will not be called
"I won't be called"
}
val value2 = myMap.getOrPut("key2", ::complexMethodToComputeValue)
println(value1)
println(value2)
这打印:
value1
I will be called
因此,回到您的代码,可以将其重写为:
fun getBitmap(id: Int) = bitmapStorage.getOrPut(id) {
BitmapFactory.decodeResource(resources, id)
}
根据您的代码,方法 getBitmap() 永远不会返回 null。在这种情况下,您会将其返回为 Bitmap(T - 类的类型)。
但是在某些情况下,方法有时可能会返回 null,在这种情况下,建议将其返回为 Bitmap? (T?)
这是 Kotlin 的美妙之处,该方法的调用者现在必须显式处理 null。 如果调用者知道它永远不可能是 null 但仍然将其注释为 T? 然后,他/她可以将其称为 getBitmap().!。
更多信息: https://kotlinlang.org/docs/reference/null-safety.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.