Search code examples
androidkotlinnullable

Remove extra if in Kotlin


How can I remove the if (savedInstanceState != null) in code below and do all with ? and !!

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

Solution

  • You can use safe access ?. on savedInstanceState and compare nullable Boolean to true:

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

    Note this will hide the search bar even when savedInstanceState is null, so it's a slightly different behavior than originally, although it seems like desired behavior given that you passed false as default to getBoolean anyway.

    By the way, Android KTX has a View.isVisible extension property that lets you write this as:

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