-1

I have two extension method

Function A is:

fun Activity.postDelay1s(run: () -> Unit) {
Handler().postDelayed({ run() }, 1000)
}

Function B is:

fun CustomRefreshLayout.setUp(containerRecycleView: RecyclerView, onResfresh: () -> Unit) {
with(this) {
    recyclerView = containerRecycleView
    setColorSchemeColors(Color.BLUE,
            Color.GREEN,
            Color.YELLOW,
            Color.RED)
    setDistanceToTriggerSync(300)
    setProgressBackgroundColorSchemeColor(Color.WHITE)
    setSize(SwipeRefreshLayout.LARGE)
    setOnRefreshListener { onResfresh() }
}

}

When I call function a I use this way postDelay1s { initData() }, but call b I need use this way swipe.setUp(trade_list, this::initData).

I want to kown what different with initData() between this::initDatain this two extension function

Zoe
  • 27,060
  • 21
  • 118
  • 148
Carl
  • 251
  • 1
  • 4
  • 13

2 Answers2

3

You can call b with a function reference as you already did (::initData) and also with a lambda like in a:

swipe.setUp(trade_list){
    initData()
}

It’s also possible to pass the lambda inside the parentheses which isn’t recommended in most cases:

swipe.setUp(trade_list, { initData() })

Documentation says:

In Kotlin, there is a convention that if the last parameter to a function is a function, and you're passing a lambda expression as the corresponding argument, you can specify it outside of parentheses

Also read this thread.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
2

Your functions take the same type in their parameters (() -> Unit), so you can use call both of them in either way.


Let's see what the first syntax does:

postDelay1s { initData() }

Here you're creating a new lambda (anonymous function), whose body consists of only a single call to the initData function. You're basically introducing an additional level of redirection into your code.

With the second syntax:

postDelay1s(this::initData)

You're passing in a reference to your initData method. This way, the initData method takes over the role that the lambda played in the previous version - the postDelay1s function will call this method directly, without the need for the additional step.


Both of these syntaxes can be used with your setUp method as well.

zsmb13
  • 85,752
  • 11
  • 221
  • 226