本文将介绍如何在 Kotlin 中实现一个 switch case。Kotlin 语言没有任何 switch 语句。相反,它支持更简单的 when 语句。它是 Kotlin 等价于 Java 的 switch 语句。替换 Kotlin 中的 switch 语句背后的想法是使代码更易于理解。但在进入 when 语句之前,让我们先看看 Java switch case 的使用。示例代码:...
使用Kotlinwhen语句,我们还可以应用分支条件。假设我们需要将一个案例与一系列选项进行匹配;我们可以使用分支条件来做到这一点。如果条件为真,则执行 case 后面的语句。这是相同的演示。 示例代码: funmain(args:Array<String>){valn =3when(n) {0->print("Invalid")1->print("Invalid")in2..4->print("Numb...
```kotlin fun getDayType(day: String): String { return when (day) { "Saturday", "Sunday" -> "休息日" // 处理多个条件,只需要用逗号分隔即可 in listOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") -> "工作日" // 使用in关键字检测集合 else -> "未知天数" // 默认分支...
The kotlin switch is one of the statements that can be used to declare the block in the code but now “when” keyword used instead of the switch block the expression also used to validate the conditions it also satisfied and applied with some other similar data types that can be instead o...
Kotlin 也没有 switch 语句,但是有功能近似的 when 语句,并且使用 when 语句也不需使用 break 语句。 例: privatefuntest(foo:Any): String {varresult =when(foo) {0->"Object equals"3,10->"Or"in11..20->"Range contains"isDate ->"Class instance"!in4..30->"Range not contain"else->"Default...
Java & Groovy & Scala & Kotlin - 20.Switch 与模式匹配,Overview本章主要介绍高级条件语句中的switch语句以及其增强版的模式匹配。Java篇Switch特点Java中switch语句功能类似if,但是switch主要用在多条件分支上。switch语句由case分支和default组成,case分支用于检
问如何在Kotlin中对多个按钮使用一个事件处理程序(我已经在java中看到了switch语句)EN您需要在MainActivity...
个人不是很推荐在代码中大量使用if语句。...案例一(简单情况)第一种简单情况就是一对一,给定一个值,返回一个值,这是C++和Java中的switch语句支持的情况。...,这个是诸如Scala中的switch和Kotlin中的when支持的情况。...经过上面的介绍,我们以后可以大大减少对if...else语句的使用了,让我们的代码更加干净一些!
在《Effective Java》中也有举例。实际上,它是更一般的函数式编程的代数数据类型,在Scala和Kotlin中是...
;// Last step: publish corresponding event.//启动servelt服务器等finishRefresh();}kotlin 代码...