Search code examples
kotlinkotlin-extensionrx-kotlin

Kotlin pass function as a parameter vs lambda implementation


I'm using the io.reactivex.rxkotlin extension function:

fun <T : Any> Observable<T>.subscribeBy(
        onError: (Throwable) -> Unit = onErrorStub,
        onComplete: () -> Unit = onCompleteStub,
        onNext: (T) -> Unit = onNextStub
        ): Disposable

And when I use this extension there is a difference if I choose to send a parameter or if I use lambda. For example

first implementation:

myObservable.subscribeBy { str ->
    // onNext
}

Second implementation:

myObservable.subscribeBy({ throwable ->
    // onError
})
  • in the first implementation the function is the onNext
  • and in the second implementation the function is the onError

And I'm not sure why.


Solution

  • From Higher-Order Functions and Lambdas:

    In Kotlin, there is a convention that if the last parameter of a function accepts a function, a lambda expression that is passed as the corresponding argument can be placed outside the parentheses:

    So in your case, you have a function that takes three optional parameters. In the first implementation:

    myObservable.subscribeBy { str -> }
    

    You're using this feature to omit parentheses for the last lambda paramter (which is onNext). However, when you use the second implementation:

    myObservable.subscribeBy({ throwable -> })
    

    Since it's within the parentheses, it must be the first parameter, unless you were to explicitly name it as the last parameter, e.g.:

    myObservable.subscribeBy(onNext = { str -> })