Search code examples
kotlinrx-javarx-kotlin

What is the difference between defer() and defer{}


I am studying RxKotlin and the question arose: what is the difference between defer() and defer{}


Solution

  • defer() and defer {} is just two ways to write the same thing. Kotlin allows some shortcuts in some specific cases to help write more readable code.

    Here is an example to rewrite some code.

    Given the following function for instance:

    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