Home > Mobile >  In Android Kotlin, when creating a dialog, the samples I've seen include "_, _ ->"
In Android Kotlin, when creating a dialog, the samples I've seen include "_, _ ->"

Time:09-04

The tutorial I'm working on gives this code:

private fun showFinalScoreDialog() {
    MaterialAlertDialogBuilder(requireContext())
        .setTitle(getString(R.string.congratulations))
        .setMessage(getString(R.string.you_scored, viewModel.score))
        .setCancelable(false)
        .setNegativeButton(getString(R.string.exit)) { _, _ ->
            exitGame()
        }
        .setPositiveButton(getString(R.string.play_again)) { _, _ ->
            restartGame()
        }
        .show()
}

The tutorial took this moment to explain "trailing lambda syntax", but didn't bother to explain the actual content of the lambda. The part that I'm clueless on is _, _ -> what is this? What does it do?

The tutorial says "...the setNegativeButton() method takes in two parameters: a String and a function, DialogInterface.OnClickListener()..."

CodePudding user response:

In your case, the -> is used for lambda expressions to separate parameters from the function body. The lambda you're writing for both buttons will be invoked when the buttons are clicked. So, the exitGame operation will execute when clicking the "NegativeButton", and the restartGame operation will execute when clicking the "PositiveButton".

When writing _ as the parameters, it basically means that you don't care about them, because they won't be used in your function body.

  • Related