首页 > 解决方案 > 在 kotlin 中如何简化?

问题描述

我正在开发一个使用 when 语句的应用程序
我怎样才能使它更短?

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

标签: kotlin

解决方案


您可以将其替换为范围检查:

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

推荐阅读