Kotlin Extension Function On a Generic Interface

563 views Asked by At

I am trying to write an extension function for a Kotlin interface that simply returns an Observable of the object. So far, this is what I have been able to do, but I don't know if it is the best way to implement this functionality.

Here is what I have defined so far:

interface Anything

inline fun <reified T : Anything> Anything.toObservable(): Observable<T> = Observable.just(this as T)

And this is the usage of that Anything interface:

sealed class Something : Anything {
    object SomethingCool : Something()
    object SomethingDumb : Something()
}

enum class Input {
    COOL,
    DUMB
}

fun getSomethingFromInput(input: Input): Observable<Something> {
    return when (input) {
        Input.COOL -> Observable.just(Something.SomethingCool) // this is the manual way of wrapping the object in an Observable
        Input.DUMB -> Something.SomethingDumb.toObservable() // this is using the new extension function
    }
}

Like I said, this works, but to me it seems like there might be a better way of implementing this that I am missing...

1

There are 1 answers

0
rtsketo On

If you are looking for a simpler way, you could do something like this:

inline fun <reified T : Something> T.toObservable(): Observable<T> = Observable.just(this as T)