Hi everyone, I’m currently trying to merge three m...
# random
p
Hi everyone, I’m currently trying to merge three method calls that alls return a specific subtype of a sealed interface into one call. The idea is to supply the expected result from the outside, so I don’t have to check the result type anymore. Here’s an example:
Copy code
sealed interface SomeResult {
    data class A(val s: String): SomeResult
    data class B(val i: Int): SomeResult
    data class C(val b: Boolean): SomeResult
}

class SomeService {
    fun request1(): SomeResult.A = TODO()
    fun request2(): SomeResult.B = TODO()
    fun request3(): SomeResult.C = TODO()
}

class MyCurrentImpl(val someService: SomeService) {
    fun blabla11(): SomeResult.A {
        //same setup, just calls request1()
        someService.request1()
        TODO()
    }
    fun blabla22(): SomeResult.B {
        //same setup, just calls request2()
        someService.request2()
        TODO()
    }
    fun blabla33(): SomeResult.C {
        //same setup, just calls request3()
        someService.request3()
        TODO()
    }
    
    //TODO: 
    // Merge all the setup & call into one method.
    // Additionally, supply result type from the outside, 
    // so I don't have 3 when statements.
    inline fun <reified T: SomeResult> getPaymentOptions(): T = 
        when {
            //Error: Type parameter 'T' is not an expression
            //Error: Required: T Found: SomeResult.B
            T is SomeResult.A -> someService.request1()
            T is SomeResult.B -> someService.request2()
            T is SomeResult.C -> someService.request3()
        }
    }
}
The important bit (in my imagination) is, that
T
always has to be of type
SomeResult
, so it’s sealed. Hence I was hoping to somehow iterate over it.. 🤔 Any ideas? Thanks in advance!
y
Copy code
when(T::class) {
  SomeResultA::class -> ...
}
p
Yeah, I tried that too, but looks like the exhaustiveness check of the
when
is then not working any more and I have to cast the result of my
request()X
call to
T
with
as T
. Currently trying to figure out why. Thanks though!