Home > Net >  How to simplify when in kotlin?
How to simplify when in kotlin?

Time:10-03

I'm working on an app which use a when statement
How can I make this more short?

when(page) {
   0 -> poster[0].imageURL
   1 -> poster[1].imageURL
   2 -> poster[2].imageURL
   3 -> poster[3].imageURL
   else -> "image not provided"
}

CodePudding user response:

You can just replace it with a range check:

if (page in 0..3) {
    poster[page].imageURL
} else {
    "image not provided"
}
  • Related