Kotlin sealed class subclass needs to be casted to base class if provided as RxJava Observable

maybe you misunderstand the generic variance in kotlin. it works fine since Success<Boolean> is a subtype of Result<Boolean>. so the "No need cast" warning reported and the code below works fine:

val ok:Success<Boolean>  = Success(true);
val result:Result<Boolean>  = ok;

But you can't assign a Success<Boolean> to a Result<Any> since their type parameters are different, so this why compiler reports the "Type mismatch" error , for example:

val ok:Success<Boolean>  = Success(true);
val result1:Result<Any>  = ok;// error
val result2:Result<out Any>  = ok;// ok

to fix the error and warnings you can try the code below:

fun getOrganization(): Observable<out Result<Boolean>> {
    return api.getOrganization("google")
            .map<Result<Boolean>> { Success(true) }
            .onErrorReturn { Failure(RuntimeException("throwable")) }
}

for more details, you can see java generic subtypes & kotlin type projections.

java generic subtype


An Observable<Success<Boolean>> is not a subtype Observable<Result<Boolean>>, just as List<String> is not a subtype of List<Object>. See the Generics documentation.

To solve this, either return an Observable<out Result<Boolean>>, or explicitly add a type to your map function:

.map<Result<Boolean>> { Success(true) }