https://kotlinlang.org logo
c

Caleb Allen

05/07/2018, 10:47 PM
I asked this in random but wondered if this was a more appropriate place to propose this: enforcing handling of a sealed class using method overloading. For example:
Copy code
class 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
Copy code
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:
Copy code
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
b

benleggiero

05/07/2018, 11:35 PM
This behavior seems more like Haskell than Kotlin… I’m not sure how you expect the compiler to know which subtype is going to be chosen at random at runtime
2 Views