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

相关推荐
Cao_Shixin攻城狮2 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
呼啦啦呼啦啦啦啦啦啦5 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
idjl7 小时前
Mysql测试题
android·adb
游戏开发爱好者89 小时前
iOS App 电池消耗管理与优化 提升用户体验的完整指南
android·ios·小程序·https·uni-app·iphone·webview
人生游戏牛马NPC1号10 小时前
学习 Flutter (四):玩安卓项目实战 - 中
android·学习·flutter
星辰也为你祝福h11 小时前
Android原生Dialog
android
梁同学与Android12 小时前
Android ---【CPU优化】需要优化的原因及优化的地方
android
Misha韩13 小时前
React Native 基础tabBar和自定义tabBar - bottom-tabs
android·react native
iHero13 小时前
【Nextcloud】在 Ubuntu 22.04.3 LTS 上的 Nextcloud Hub 10 (31.0.2) 后台任务cron 的优化
android·linux·ubuntu·nextcloud
yuanlaile17 小时前
Flutter Android打包学习指南
android·flutter·flutter打包·flutter android