Philipp Mayer
09/19/2022, 9:08 AMsealed 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!Youssef Shoaib [MOD]
09/19/2022, 10:34 AMwhen(T::class) {
SomeResultA::class -> ...
}
Philipp Mayer
09/19/2022, 11:31 AMwhen
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!