https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

09/22/2020, 7:26 PM
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

nanodeath

09/22/2020, 7:40 PM
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

Daniele B

09/22/2020, 7:45 PM
thanks! yes, I think I will keep the named variable
c

Cedrick Cooke

09/22/2020, 7:52 PM
Another alternative, something like this should work
Copy code
when (val changed = changeSelectedCounty()) {
    true -> showDetail()
}
b

Brian Dilley

09/22/2020, 8:31 PM
Copy code
changeSelectedCounty() ?: showDetail()
1
not sure if that would work actually
n

nanodeath

09/22/2020, 8:36 PM
that'll only execute
showDetail
if
changed
is null
i

itbhp

09/23/2020, 3:58 AM
Add a query method countyChanged that calls the command method 'changeSelectedCountry' and return the outcome, then use it instead of a local variable
a

Akindele Beulah

09/23/2020, 10:39 AM
@Brian Dilley Kotlin has tenary?
i

itbhp

09/23/2020, 10:55 AM
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

Brian Dilley

09/23/2020, 6:29 PM
right, no ternary and it’s a null thing
btw:
Copy code
val changed = if (changeSelectedCountry()) { true } else { false }
👎 1
n

nanodeath

09/23/2020, 6:36 PM
I mean, you can, but why
2 Views