2

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?

fawaad
  • 341
  • 6
  • 12
grepx
  • 443
  • 5
  • 7

1 Answers1

6

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.


To fix your code, you can just remove = from your function declaration:
fun Subscription.addToComposite(composite: CompositeSubscription) { composite.add(this) }
Community
  • 1
  • 1
hotkey
  • 140,743
  • 39
  • 371
  • 326