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

sreich

02/26/2017, 12:55 PM
i don't suppose there's a way to say
when (foo) { != 0 -> stuff(); else -> blah() }
, while still using the var specifier, aka the
(foo)
b

bernhard

02/26/2017, 1:10 PM
sreich: I suppose your real usecase is much more complicated, but just swap the branches
s

sreich

02/26/2017, 1:11 PM
Yeah there's a few more branches
b

bernhard

02/26/2017, 1:12 PM
another hacky approach would be
!in 0..0
a

Andreas Sinz

02/26/2017, 1:24 PM
you just need to use
var foo
inside when?
s

sreich

02/26/2017, 3:05 PM
Eh inside where?
b

bernhard

02/26/2017, 4:17 PM
Copy code
when (foo) {
   5 -> onlyWhenFive()
   foo != 0 -> stuff()
   else -> blah()
}
would still be possible EDIT: okay, that's not valid, wasn't aware that you can't mix when expressions types... I thought it would be as mighty as in scala but there seems to be a quite big gap
s

sreich

02/26/2017, 4:29 PM
And you can't just do !0 in the branch can you?
b

bernhard

02/26/2017, 4:51 PM
nope, that's not possible either. there are no boolean expressions on the argument passed to when, just the kotlin keywords
in
and
is
either you use foo in every branch for boolean expressions (either all are boolean or all are the corresponding type of the when argument) or as a hack
!in 0..0
where you create a range for [0]
g

groostav

02/26/2017, 10:46 PM
just so we're clear, the fully verbosity is
Copy code
when {
  foo == 5 -> onlyWhenFive()
  foo != 0 -> stuff()
  else -> blah()
}
so the thing we're trying to eliminate here is a couple of extra
foo
_expr_'s. I could've sworn there were some issues for this but I cant find them now