【问题标题】:kotlin return type of nullable?.let{}kotlin 返回类型为 null?.let{}
【发布时间】:2021-06-15 17:55:03
【问题描述】:

我是 Kotlin 的新手,从几天开始我就在 android studio 上玩了一下。这是我正在处理的课程:

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

    }

}

我不明白返回的是什么

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

我知道有趣的是 onCreateDialog 返回一个“Dialog”对象,因为

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog 

正在返回一个对话框类型(代码实际上是有效的),但我不明白在这种情况下“返回”是如何工作的,我是否返回了所有括号内容?谢谢大家!

【问题讨论】:

    标签: android kotlin dialog nullable return-type


    【解决方案1】:

    let 返回其中最后一个表达式的结果,在本例中为 builder.create() 的值,一个不可为空的 AlertDialog。

    由于您使用?.let,如果activity 为空,let 将不会被调用,而您实际上将拥有null ?: throw...

    builder.create() 永远不会返回 null,所以这个 throw 表达式只有在 activity 为 null 时才会到达,因此错误消息没有意义。

    【讨论】:

    • 还有一点,onCreateDialog() 除非当前附加到活动,否则不会被调用,因此可以剥离整个 ?.let,而可以使用 AlertDialog.Builder(requireActivity())
    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多