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也有相似之处,目的都是为了开发简化。

相关推荐
CYRUS_STUDIO2 小时前
使用 AndroidNativeEmu 调用 JNI 函数
android·逆向·汇编语言
梦否2 小时前
【Android】类加载器&热修复-随记
android
徒步青云2 小时前
Java内存模型
android
今阳2 小时前
鸿蒙开发笔记-6-装饰器之@Require装饰器,@Reusable装饰器
android·app·harmonyos
-优势在我7 小时前
Android TabLayout 实现随意控制item之间的间距
android·java·ui
hedalei7 小时前
android13修改系统Launcher不跟随重力感应旋转
android·launcher
Indoraptor8 小时前
Android Fence 同步框架
android
峥嵘life9 小时前
DeepSeek本地搭建 和 Android
android
叶羽西9 小时前
Android14 Camera框架中Jpeg流buffer大小的计算
android·安卓
jiasting9 小时前
Android 中 如何监控 某个磁盘有哪些进程或线程在持续的读写
android