How can I write this code without repeating `chang...
# getting-started
d
How can I write this code without repeating
changed
twice ?
Copy code
val changed = changeSelectedCounty()
if (changed) {
    showDetail()
}
I am looking for something like this, but it’s not accepted:
Copy code
if (val changed = changeSelectedCounty()) {
    showDetail()
}
I would to assign the result to the
changed
variable, as it gives more clarity
n
I can think of a goofy way...
Copy code
changeSelectedCounty().takeIf { changed -> changed }?.let { showDetail() }
but that's almost certainly confusing
oh, if you want to be really explicit you can return an enum
Copy code
if (changeSelectedCounty() == CHANGE_OCCURRED) { showDetail() }
but...might be overkill
tbh I think just using a named variable is fine. "Clean Code" recommends creating more variables than you strictly need to for documentation purposes.
d
thanks! yes, I think I will keep the named variable
c
Another alternative, something like this should work
Copy code
when (val changed = changeSelectedCounty()) {
    true -> showDetail()
}
b
Copy code
changeSelectedCounty() ?: showDetail()
1
not sure if that would work actually
n
that'll only execute
showDetail
if
changed
is null
i
Add a query method countyChanged that calls the command method 'changeSelectedCountry' and return the outcome, then use it instead of a local variable
a
@Brian Dilley Kotlin has tenary?
i
Brian's code is not an example of a ternary operator: the ?: I think it is called Elvis operator. It is used to do something when the left part is null.
And no Kotlin doesn't have ternary operator
b
right, no ternary and it’s a null thing
btw:
Copy code
val changed = if (changeSelectedCountry()) { true } else { false }
👎 1
n
I mean, you can, but why