【问题标题】:What is the difference between defer() and defer{}defer() 和 defer{} 有什么区别
【发布时间】:2021-10-10 12:45:53
【问题描述】:

我正在研究 RxKotlin,问题出现了:defer()defer{} 之间有什么区别

【问题讨论】:

    标签: kotlin rx-java rx-kotlin


    【解决方案1】:

    defer()defer {} 只是写同一件事的两种方式。 Kotlin 在某些特定情况下允许使用一些快捷方式来帮助编写更具可读性的代码。

    这是一个重写一些代码的例子。

    例如给定以下函数:

    fun wrapFunctionCall(callback: (Int) -> Int) {
       println(callback(3))
    }
    
    wrapFunctionCall(x: Int -> {
      x * x
    })
    
    // Most of the time parameter type can be infered, you can then let it go
    wrapFunctionCall(x -> {
      x * x
    })
    
    // Can omit parameter, and let it be name `it` by default
    wrapFunctionCall({
      it * it
    })
    
    // wrapFunctionCall accepts a lambda as last parameter, you can pull it outside the parentheses. And as this is the only parameter, you can also omit the parenthesis
    wrapFunctionCall {
      it * it
    }
    

    https://kotlinlang.org/docs/lambdas.html#function-types

    【讨论】:

      【解决方案2】:

      两个函数都是一样的,区别在于Kotlin语法。

      如果一个函数接收一个函数作为最后一个参数,它可以在括号外传递。详情请参阅the documentationthis answer

      但是我不知道 RxKotlin 的详细信息。

      【讨论】:

        猜你喜欢
        • 2015-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-15
        • 2012-01-28
        • 2013-02-23
        • 1970-01-01
        相关资源
        最近更新 更多