I've been playing with Kotlin/RxJava and tried to create an extension method for adding a Subscription
to a CompositeSubscription
, that would work like:
search.subscribe {
//do stuff
}.addToComposite(compositeSubscription)
This is my attempt so far:
fun Subscription.addToComposite(composite: CompositeSubscription) = { composite.add(this) }
It compiles and runs without errors but doesn't seem to actually add the Subscription
to the CompositeSubscription
. Am I doing something wrong?
Your function is defined incorrectly. Compare:
fun f() { println("hello") }
This function executes the single statement println("hello")
and is a simple Unit
-returning function (same to void
in Java).
fun g() = { println("hello") }
This function is a single-expression function, it just returns value of expression { println("hello") }
, that is a lambda expression. g
's return type is () -> Unit
, and it doesn't execute the lambda body!
This is also explained here.
=
from your function declaration:
fun Subscription.addToComposite(composite: CompositeSubscription) { composite.add(this) }