Smart cast impossible in a coroutine context?

The work-around is to move type declaration in load function to the async builder like this:

fun load() = async<List<Pizza>> { ... }

I’ve created a ticket for this problem: https://youtrack.jetbrains.com/issue/KT-20817

As a matter of style, I highly recommend to include “async” into the name of functions that return Deferred<Something> or rather declare them as suspending functions and avoid the use of futures altogether, which makes the code easier to read/understand, faster, and less error-prone. I this case I’d rewrite it like this (no need to use async nor qualified returns at all):

class PizzasRepository {
    suspend fun load(): List<Pizza> =
        loadFromCache() ?: loadFromApi()

    private fun loadFromCache(): List<Pizza>? = TODO()
    private suspend fun loadFromApi(): List<Pizza> = TODO()
}
2 Likes