Pathuri Naveena
Pathuri Naveena

Reputation: 1

How to replace the 'When' statement to a simple ternary statement in kotlin

1.Can I simplify the code in when statement to one or two lines.I am trying to replace the code in the when block but unable to do it.

// Loads all the settings changed in the theme
    override fun onCreate() {
        super.onCreate()

        var sharedPreferences = getSharedPreferences(
            CatalystConstants.keyThemeObject,
            AppCompatActivity.MODE_PRIVATE
        )

        when (sharedPreferences.getInt(CatalystConstants.prefName, CatalystConstants.themeLight)) {
            CatalystConstants.themeLight -> {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
            CatalystConstants.themeDark -> {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            }
        }
    }
}```

Upvotes: 0

Views: 65

Answers (2)

Tenfour04
Tenfour04

Reputation: 93834

If there are only two possible values, you can do this, although in my opinion when would be much clearer to read because the comparison is so long.

appCompatDelegate.defaultNightMode = if(sharedPreferences.getInt(CatalystConstants.prefName, CatalystConstants.themeLight) 
                == CatalystConstants.themeLight)
            AppCompatDelegate.MODE_NIGHT_NO
        else // themeDark
            AppCompatDelegate.MODE_NIGHT_YES

With when:

appCompatDelegate.defaultNightMode = 
    when (sharedPreferences.getInt(CatalystConstants.prefName, CatalystConstants.themeLight)) {
            CatalystConstants.themeLight -> AppCompatDelegate.MODE_NIGHT_NO
            CatalystConstants.themeDark -> AppCompatDelegate.MODE_NIGHT_YES
        }

Could be more concise using run. It's not very clear, but that's because you aren't using all caps for your constant names:

CatalystConstants.run { 
    appCompatDelegate.defaultNightMode = 
        when (sharedPreferences.getInt(prefName, themeLight)) {
                themeLight -> AppCompatDelegate.MODE_NIGHT_NO
                themeDark -> AppCompatDelegate.MODE_NIGHT_YES
            }
}

Upvotes: 2

Teku
Teku

Reputation: 35

There is not if-else ternary expresion in Kotlin but you can write if-else statment in this way:

if (a > b) a else b

It's the most similar way to ternary if-else

Upvotes: 0

Related Questions