返回非空类型

问题描述 投票:0回答:1

我确定,我的代码返回的值不是空值:

    fun getBitmap(id: Int): Bitmap{
        if (!(id in bitmapStorage))
            bitmapStorage.put(id, BitmapFactory.decodeResource(resources, id))
        return bitmapStorage.get(id)
    }

返回Bitmap类型而不是Bitmap?的正确方法是什么?

[!!as Bitmap或其他?

kotlin
1个回答
0
投票

您可以使用!!运算符或MutableMap的API-getOrPut,它将返回非null类型

fun getBitmap(id: Int): Bitmap{
    return bitmapStorage.getOrPut(id) {BitmapFactory.decodeResource(resources, id)}
}

请注意,如果同时修改地图,则不能保证该操作是原子操作。

© www.soinside.com 2019 - 2024. All rights reserved.