密封类(sealed class)

   密封类:使用关键字 sealed,密封类里面可以有若干个子类,这些子类如果要继承密封类,

    则必须和密封类在同一个文件里

sealed class LicenseStatus2 {
    //单例继承密封类
    object UnQualified : LicenseStatus2()
    //单例继承密封类
    object Learning : LicenseStatus2()
    //子类继承密封类
    class Qualified(val licenseId: String) : LicenseStatus2()

}

class Driver2(var status: LicenseStatus2) {
    fun checkLicense(): String {
        return when(status){
            is LicenseStatus2.UnQualified -> "没资格"
            is LicenseStatus2.Learning -> "在学"
            is LicenseStatus2.Qualified -> "有资格,驾驶证编号:${(this.status as LicenseStatus2.Qualified).licenseId}"
        }
    }
}

fun main() {
    val status = LicenseStatus2.Qualified("238239329")
    val driver = Driver2(status)
    println(driver.checkLicense())
}

你可能感兴趣的:(kotlin,android)