ReactiveX / RxKotlin

RxJava bindings for Kotlin
Apache License 2.0
7.01k stars 454 forks source link

Operator funs for invoking actions and funcs? #191

Open TWiStErRob opened 5 years ago

TWiStErRob commented 5 years ago

Things like:

inline operator fun Action0.invoke(): Unit =
    this.call()

inline operator fun <T> Action1<T>.invoke(input: T): Unit =
    this.call(input)

inline operator fun <T, R> Func1<in T, out R>.invoke(input: T): R =
    this.call(input)

inline operator fun <T1, T2, R> Func2<in T1, in T2, out R>.invoke(input1: T1, input2: T2): R =
    this.call(input1, input2)

so we can do:

val block: Func1<in T, out R>
val arg: T = ...
val result: R = block(arg)

as if they were Kotlin function types

TWiStErRob commented 5 years ago

Additionally these may be helpful:

inline fun (() -> Unit).toAction() = Action0 { this() }
inline fun <T> ((T) -> Unit).toAction() = Action1<T> { this(it) }
inline fun <T, R> ((T) -> R).toFunc() = Func1<T, R> { this(it) }
thomasnield commented 5 years ago

Do we even manually invoke these functional types that often? I'm struggling to see practical use cases here.

Also, I don't see value in those toAction() extensions since SAM handling takes care of lambda conversion for us.

TWiStErRob commented 5 years ago

Not in all cases, I'll show you examples when I get the chance. These all came from a need I had. We'll see if it makes sense.