https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dave08

04/25/2021, 12:57 PM
Is the only reason to use 
: Any
 in generics to prevent nulls?
I have something like:
Copy code
interface UseCase<in Request : Any, out Response : Any> {
    suspend fun execute(request: Request): Response
}
and in certain cases I need the Response to be nullable, and in others not. How can I implement such a Spy:
Copy code
class UseCaseSpy<Request : Any, Response>(
    private val returnIfNoResponse: (suspend (Request) -> Response)? = null,
    private val allowNullResponse: Boolean = false
): UseCase<Request, Response> {
    var request: Request? = null
    var responseToReturn: Response? = null

    override suspend fun execute(request: Request): Response {
        this.request = request

        val response =  responseToReturn ?: returnIfNoResponse?.invoke(request)

        if (response == null && !allowNullResponse)
            error("Either responseToReturn or returnIfNoResponse needs to be provided.")

        return response
    }
}
execute
needs to return
Response?
whether my actual type is nullable or not... so it just doesn't compile
y

Youssef Shoaib [MOD]

04/25/2021, 1:38 PM
You need to define the interface like this:
Copy code
interface UseCase<in Request : Any, out Response : Any> {
    suspend fun execute(request: Request): Response?
}
Then it should all work fine hopefully
d

dave08

04/25/2021, 1:48 PM
Nope, response still with red squiggly...
It wants the
Response
being returned from exectute to be
Response?
Doesn't seem possible for the compiler to infer such things...
But like you said, removing the
: Any
from the interface works... just for the
UseCaseSpy
I'm forced to return
Response?
...