Search code examples
androidkotlindialognullablereturn-type

kotlin return type of nullable?.let{}


I'm new to Kotlin and i'm playing a bit with android studio from few days. This is the class i'm dealing with:

class MyDialog : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        return activity?.let {
            val builder = AlertDialog.Builder(it)
            builder.setMessage(R.string.exit)
            builder.setPositiveButton(R.string.positive) { _: DialogInterface, _: Int -> }
            builder.create()
        } ?: throw Exception("problem detected with throw Exception on creating Dialog")

    }

}

I'm not understanding what is returning

return activity?.let {
            val builder = AlertDialog.Builder(it)
            builder.setMessage(R.string.exit)
            builder.setPositiveButton(R.string.positive) { _: DialogInterface, _: Int -> }
            builder.create()
        } ?: throw Exception("problem detected with throw Exception on creating Dialog")

I know the fun onCreateDialog returns a "Dialog" object because

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog 

is returning a Dialog type (the code works in fact), but i don't understand how the "return" works in that case, am i returning all the brackets content? Thx everyone!


Solution

  • let returns the result of last expression inside it, in this case the value of builder.create(), a non-nullable AlertDialog.

    Since you use ?.let, if activity is null, let won't be called, and you will effectively have null ?: throw....

    builder.create() never returns null, so this throw expression is only reached when activity is null, so the error message doesn't make sense.