Ellen Spertus
06/08/2020, 10:27 PMif (intent.getStringExtra(SUGGESTION_KEY) != null) {
suggestionButton.text = intent.getStringExtra(SUGGESTION_KEY)
suggestionButton.visibility = View.VISIBLE
} else {
suggestionButton.visibility = View.INVISIBLE
}
I can’t write the following, because one arm returns a String and the other Unit :
intent.getStringExtra(SUGGESTION_KEY)?.let { suggestion ->
suggestionButton.text = suggestion
suggestionButton.visibility = View.VISIBLE
} ?: suggestionButton.visibility = View.INVISIBLE
(I know there is a function intent.hasStringExtra(), but I’d like a general solution not specific to intents.)
How should I rewrite the original block of code, or is it best as is?Casey Brooks
06/08/2020, 10:30 PMrun { } for the second arm (?.let { ... } ?: run { ... }). Though I think the original example is more clear (maybe just drop intent.getStringExtra into a temporary variable to avoid the double lookup)Ellen Spertus
06/08/2020, 10:32 PMlet ?: run do the trick? (I’ll stick with the original code but want to understand.)Casey Brooks
06/08/2020, 10:35 PM?: need an expression to return a value. Variable assignment is not an expression and cannot return a value, which is why the compiler chokes on it. Wrapping that assignment in run { } turns it into a Unit-returning expressionEllen Spertus
06/08/2020, 10:36 PMrun, the compiler knows the overall expression should return Unit (even if one path returns a value)?bezrukov
06/08/2020, 10:36 PMrun can return any type as wellbezrukov
06/08/2020, 10:40 PMisInvisible extension from ktx, in this case you can avoid branches.
val suggestion = intent.getStringExtra(SUGGESTION_KEY)
suggestionButton.text = suggestion
suggestionButton.isInvisible = suggestion == nullEllen Spertus
06/08/2020, 10:41 PMisInvisible, although there’s more code in the then-body than I showed.Ellen Spertus
06/08/2020, 10:48 PMbezrukov
06/08/2020, 10:48 PMbezrukov
06/08/2020, 10:49 PMsome code ?: some more code both parts must be expressionEllen Spertus
06/08/2020, 10:50 PMbezrukov
06/08/2020, 10:50 PMreturn Unit to itlouiscad
06/09/2020, 6:32 AM