Caleb Allen
05/07/2018, 10:47 PMclass ResponseHandler{
fun handle(success: Response.Success) {}
fun handle(error: Response.ErrorB) {}
fun handle(error: Response.ErrorA) {}
}
fun getResponse(): Response{
val r = Random()
return when (r.nextInt(3)) {
0 -> { Response.Success() }
1 -> { Response.ErrorA() }
2 -> { Response.ErrorB() }
else -> { throw IllegalStateException() }
}
}
And then calling
ResponseHandler().handle(getResponse())
This will not compile. The same effect can be achieved using if I implemented a method taking a Response
parameter like so:
fun handle(response: Response) = when (response) {
is Response.Success -> { handle(response) }
is Response.ErrorA -> { handle(response) }
is Response.ErrorB -> { handle(response) }
}
Is it possible for the compiler to resolve the type for me? Given that all possible types are handled, similar to when
benleggiero
05/07/2018, 11:35 PM