How should I handle a value that should be ignored...
# announcements
s
How should I handle a value that should be ignored in a
when
statement? in fx this situation
Copy code
enum Foo { FOO, BAR, FOOBAR }

val foo = ...
when(foo) {
  FOO -> sayFoo()
  BAR -> sayBar()
  FOOBAR -> do nothing
}
s
Unit
should work, I’m pretty sure
l
unit works, but also if you are returning nothing you can also simply omit the FOOBAR clause
d
Copy code
when(foo) {
  FOO -> sayFoo()
  BAR -> sayBar()
}
or
Copy code
when(foo) {
  FOO -> sayFoo()
  BAR -> sayBar()
  FOOBAR -> Unit
}
k
don’t add FOOBAR in
when
1
s
iirc the IDE warns even if you aren’t using
when
as an expression and miss an enum value
or, at least, maybe it used to
s
oki, thanks! Must've been a mistake when I was trying out what to do, because I remember the IDE giving an error about missing values. but it seems to work fine omitting FOOBAR now.. weird.. thanks!
k
👍
l
you will get an error if you do something like
Copy code
val ret = when(foo) {
  FOO -> sayFoo()
  BAR -> sayBar()
}
statement doesn’t require exhaustive coverage, expression does
s
Yes. that must've been it
c
You can also use an empty code block, which I find a bit more understandable
Copy code
when(foo) {
    FooBar.FOO -> sayFoo()
    FooBar.BAR -> sayBar()
    FooBar.FOOBAR -> {}
}
2