简体   繁体   中英

Return non-nullable type

I'm sure, my code gets not null value for return:

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

What's the right way to return Bitmap type instead of Bitmap? ?

!! , as Bitmap or something else?

You can use !! operator or API of MutableMap - getOrPut , it'll return non-null type

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

Note that the operation is not guaranteed to be atomic if the map is being modified concurrently.

Given the operations you're performing on bitmapStorage I'm assuming it's an instance of MutableMap . If that's the case, I think there's an even more idiomatic way to achieve the same result, and it involves using getOrPut method . Basically, it returns the value associated to a given key, if it exists, otherwise it associates whatever value you want to the given key and returns that value.

Example:

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)

This prints:

value1
I will be called

So, to come back to your code, it could be rewritten as:

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

As per your code, the method getBitmap() can never return null. In such cases, you'd return it as Bitmap (T - type of class).

But there could be cases, where a method can potentially return null at times, in such cases it is advised to return it as Bitmap? (T?)

And here is the beauty of Kotlin gets to shine, the caller of the method now has to handle the null explicitly. If the caller knows that it can never be null but still has annotated it as T? then, he/she can call it as getBitmap().!.

More on it: https://kotlinlang.org/docs/reference/null-safety.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM