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

相关推荐
飘逸飘逸1 小时前
Autojs进阶前言
android·javascript
spencer_tseng1 小时前
Branding Printing System (Android Pad)
android·pad
FrameNotWork2 小时前
多设备 Android Logcat 自动采集方案:基于 Docker + Shell 实现日志按天切割与自动清理
android·docker·容器
bqliang3 小时前
Compose 实验性 Styles API
android·android jetpack
大尚来也4 小时前
PHP 入门指南:从零基础到掌握核心语法
android
summerkissyou19874 小时前
android -wifi/蓝牙-常见面试题
android·wifi·bluetooth
XiaoLeisj4 小时前
Android Activity 页面导航基础:Manifest 声明、Intent 显式/隐式跳转与数据传递
android·java
littlegnal5 小时前
Flutter Android如何延迟加载代码
android·flutter
秋氘渔5 小时前
MySQL EXPLAIN实战:6种索引失效场景验证与优化
android·数据库·mysql·索引