[英]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.