android kotlin基础复习—if when

1、新建kt并运行

  • 新建文件kt
  • 运行文件kt

2、kotlin语句 if when的使用

复制代码
var x = 5
    val y = 9
    if (x in 1..8) {
        println("x 在区间内")
    }

说明:

var:定义变量 val定义常量。

代码中会看到那个<=,也就是说包括1,8。

3、输出

4、所有代码,可以测试:

复制代码
fun main(args: Array<String>) {
    var x = 5
    val y = 9
    if (x in 1..8) {
        println("x 在区间内")
    }

    x = 0
    when (x) {
        0, 1 -> println("x == 0 or x == 1")
        else -> println("otherwise")
    }

    when (x) {
        1 -> println("x == 1")
        2 -> println("x == 2")
        else -> { // 注意这个块
            println("x 不是 1 ,也不是 2")
        }
    }

    when (x) {
        in 0..10 -> println("x 在该区间范围内")
        else -> println("x 不在该区间范围内")
    }

    val validNumbers= arrayListOf(1,2)
    when (x) {
        in 1..10 -> print("x is in the range")
        in validNumbers -> print("x is valid")
        !in 10..20 -> print("x is outside the range")
        else -> print("none of the above")
    }

    val items = setOf("apple", "banana", "kiwi")
    when {
        "orange" in items -> println("juicy")
        "apple" in items -> println("apple is fine too")
    }

    println(hasPrefix("prefix_9023"))
}

fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}

5、kotlin语法并不难,与swift也有相似之处,目的都是为了开发简化。

相关推荐
Android-Flutter2 小时前
android 动画详解
android·kotlin
小孔龙7 小时前
GraphicBuffer 跨进程共享
android
行业研究员7 小时前
Android内置GPS与腾讯地图定位技术对比分析
android·android定位·腾讯地图定位
Android-Flutter8 小时前
android WMS 详解(二)
android·kotlin
游戏开发爱好者89 小时前
App Store 上传 IPA 自动化,.p8 密钥认证与 CI/CD 接入实战
android·运维·ci/cd·小程序·uni-app·自动化·iphone
游戏开发爱好者810 小时前
iOS 推送怎么配置,APNs 推送证书、设备库与群发
android·ios·小程序·https·uni-app·iphone·webview
阿pin10 小时前
Android随笔-kotlin 高阶函数
android·kotlin·高阶函数
wxson72821 天前
【Android视频监控系统技术总结】
android·音视频
hunterandroid1 天前
[Android 从零到一] LiveData 粘性事件与单次消费:从重复触发到可靠事件总线
android