kotlin 密封类

密封类,限制了有哪些子类,所有子类都在一个文件中。写个简单demo测试下:

Kotlin 复制代码
// HuManStatus是密封类,表示一个人想要做什么的状态
sealed class HuManStatus {
    data class WashFeet(val costMoney: Double): HuManStatus() // 子类,表示花钱洗脚
    data class AnMo(val costMoney: Double): HuManStatus() // 子类,表示花钱按摩
    object Sleep: HuManStatus() // 单例对象,表示睡觉
}

fun dealWithHuManStatus(status: HuManStatus):Unit {
    when (status) {
        is HuManStatus.WashFeet -> println("花费${status.costMoney}洗个脚")
        is HuManStatus.AnMo -> println("花费${status.costMoney}按个摩")
        HuManStatus.Sleep -> println("没带钱,只能回家睡觉")
    }
}

fun main() {
    for (i in 0..5) {
        val money = (0..1000).random()
        if (money >= 700) {
            dealWithHuManStatus(HuManStatus.WashFeet(money.toDouble()))
        } else if (money >= 300) {
            dealWithHuManStatus(HuManStatus.AnMo(money.toDouble()))
        } else {
            dealWithHuManStatus(HuManStatus.Sleep)
        }
    }
}

打印:

ok.

相关推荐
Kapaseker10 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z2 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton3 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream3 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam3 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker4 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言