Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Android Kotlin, when creating a dialog, the samples I've seen include "_, _ ->" what does that mean or do?

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()…"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading