Kotlin pass function as a parameter vs lambda implementation

时间:2019-03-19 15:13:19

标签: kotlin kotlin-extension rx-kotlin

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.

2 个答案:

答案 0 :(得分:7)

来自Higher-Order Functions and Lambdas

  

在Kotlin中,有一个约定,如果函数的最后一个参数接受函数,则可以将作为相应参数传递的lambda表达式放在括号之外:

因此,在您的情况下,您有一个带有三个可选参数的函数。在第一个实现中:

myObservable.subscribeBy { str -> }

您正在使用此功能来省略 last lambda参数(即onNext)的括号。但是,当您使用第二种实现时:

myObservable.subscribeBy({ throwable -> })

因为它在括号内,所以它必须是第一个参数,除非您明确地将其命名为最后一个参数,例如:

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

答案 1 :(得分:1)

subscribeBy方法具有命名参数的优点,它将解决所有问题。

您会发现,使用lambda表示法设置的是最后一个未命名的参数,而设置参数则直接设置了第一个未命名的参数。

如果您命名参数之一,则将无法再使用lambda表示法。