https://kotlinlang.org logo
#announcements
Title
# announcements
r

rook

05/24/2017, 5:08 PM
Does elvis operator work with boolean checks? I currently have
remote.foo != null && remote.foo != local.foo
I’m trying to simplify it to something like
remote.foo != local.foo ?: false
but it seems like the elvis operator can’t be used that way
k

kingsley

05/24/2017, 5:40 PM
nukeforum: no. The Elvis operator doesn't work this way. Meanwhile, you can just do
remote?.foo != local.foo
nukeforum: However, a close replication of your example could be:
remote?.let { it.foo != local.foo } ?: false
r

rook

05/24/2017, 5:43 PM
so,
local
and
remote
are non-null, but in either case
foo
is nullable. I need the entire check to default to
false
if
remote.foo
is null without having the entire separate clause to check it
ah, yeah, I thought about using
let
, but it ends up being about the same amount of characters 😓
k

kingsley

05/24/2017, 5:52 PM
Ah. Sorry. I missed that. Doesn't look like you have much options
If it were to be in a function though, one could split this into 2 lines and have something like this:
Copy code
fun checkFoo(remote: Bar, local: Bar) : Boolean {
  val remoteFoo = remote.foo ?: return false
  return remoteFoo != local.foo
}
r

rook

05/25/2017, 1:25 PM
Thanks for your help!
2 Views