在 Kotlin 中删除额外的 if

Remove extra if in Kotlin

我如何删除下面代码中的 if (savedInstanceState != null) 并使用 完成所有操作?和 !!

override fun onViewStateRestored(savedInstanceState: Bundle?) {
        super.onViewStateRestored(savedInstanceState)
        if (savedInstanceState != null)
            search_bar.visibility =
                    if (savedInstanceState.getBoolean("showSearchBar", false)) View.VISIBLE else View.GONE
    }

您可以在 savedInstanceStatecompare nullable Boolean to true 上使用安全访问 ?.

val showSearchBar = savedInstanceState?.getBoolean("showSearchBar", false) == true
search_bar.visibility = if (showSearchBar) View.VISIBLE else View.GONE

请注意,即使 savedInstanceState 为 null,这也会隐藏搜索栏,因此它的行为与最初的行为略有不同,尽管这似乎是您将 false 作为默认值传递给 getBoolean 无论如何。

顺便说一下,Android KTX 有一个 View.isVisible 扩展名 属性 可以让你这样写:

search_bar.isVisible =
    savedInstanceState?.getBoolean("showSearchBar", false) == true