Kotlin 返回不可为空的类型
我确信,我的代码返回的值不是空值:Kotlin 返回不可为空的类型,kotlin,Kotlin,我确信,我的代码返回的值不是空值: fun getBitmap(id:Int):位图{ 如果(!(位图存储中的id)) bitmapStorage.put(id,BitmapFactory.decodeResource(resources,id)) 返回bitmapStorage.get(id) } 返回位图类型而不是位图的正确方法是什么? ,作为位图或其他什么?您可以使用运算符或可变映射的API-getOrPut,它将返回非空类型 fun getBitmap(id: Int): Bitmap
fun getBitmap(id:Int):位图{
如果(!(位图存储中的id))
bitmapStorage.put(id,BitmapFactory.decodeResource(resources,id))
返回bitmapStorage.get(id)
}
返回位图
类型而不是位图的正确方法是什么?
编码>,作为位图
或其他什么?您可以使用代码>运算符或可变映射的API-getOrPut
,它将返回非空类型
fun getBitmap(id: Int): Bitmap{
return bitmapStorage.getOrPut(id) {BitmapFactory.decodeResource(resources, id)}
}
请注意,如果同时修改映射,则不能保证操作是原子的。根据您的代码,getBitmap()方法永远不能返回null。在这种情况下,您可以将其作为位图(类的T类型)返回
但在某些情况下,方法有时可能返回null,在这种情况下,建议将其作为位图返回?(T?)
这就是Kotlin的魅力所在,方法的调用方现在必须显式地处理null。如果调用方知道它永远不能为null,但仍然将其注释为T?然后,他/她可以将其称为getBitmap()
更多信息:鉴于您在bitmapStorage
上执行的操作,我假设它是MutableMap
的一个实例。如果是这样的话,我认为有一种更惯用的方法可以达到同样的效果,它包括使用。基本上,它返回与给定键(如果存在)关联的值,否则它会将您想要的任何值关联到给定键并返回该值
例如:
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)
因此,回到您的代码,它可以重写为:
fun getBitmap(id: Int) = bitmapStorage.getOrPut(id) {
BitmapFactory.decodeResource(resources, id)
}
运算符是正确的方法,但是您必须确保结果从不为null,否则它将抛出运行时异常
fun getBitmap(id: Int) = bitmapStorage.getOrPut(id) {
BitmapFactory.decodeResource(resources, id)
}