美文网首页
kotlin 密封类sealed class

kotlin 密封类sealed class

作者: Bfmall | 来源:发表于2022-11-12 21:18 被阅读0次

sealed class密封类学习笔记###

/**
 * DESC   : sealed class密封类
 */

const val KtBaseSealedTest01_TAG = "KtBaseSealedTest01"

/**
 * 密封类:成员要有类型,并且必须继承本类
 *
 *
 * 测试:找出优秀学生的姓名
 * 如果使用枚举来找到优秀学生的姓名,就比较麻烦了,不是做不到,
 * 而是有更简单的办法,就是引入密封类
 */
sealed class Exam2 {
    //score1,score2,score3都不需要任何成员,所以一般都写成object
    object score1 : Exam2() //不及格
    object score2 : Exam2() //及格
    object score3 : Exam2() //良好

    //假设 score4也写成object类型,也不合理,因为对象不是单例的,studentName可能是 zhangsan,可能是lisi...等等
    class score4(val studentName: String) : Exam2() //优秀
}

class Teacher2(val exam: Exam2) {
    /**
     * 显示学生考试成绩
     */
    fun showStudentExamInfo() : String {
        return when(exam) {
            is Exam2.score1 -> "此学生考试不及格"
            is Exam2.score2 -> "此学生考试及格"
            is Exam2.score3 -> "此学生考试良好"
            is Exam2.score4 -> "此学生考试优秀:学生姓名:"+(exam as Exam2.score4).studentName

            /**
             * 由于showStudentExamInfo函数是使用枚举类型来进行判断处理的,这个属于 代数数据类型,
             * 就不需要写else了, 因为when表达式非常明确,就只有4种枚举类型,不会出现其他情况,所以不需要写else
             */
//            else -> ""
        }
    }
}

class KtBaseSealedTest01 {

    fun testSealed01() {
        /**
         * testSealed01==>此学生考试不及格
         * testSealed01==>此学生考试及格
         * testSealed01==>此学生考试良好
         * testSealed01==>此学生考试优秀:学生姓名:马云
         */
        Log.d(KtBaseSealedTest01_TAG, "testSealed01==>"+Teacher2(Exam2.score1).showStudentExamInfo())
        Log.d(KtBaseSealedTest01_TAG, "testSealed01==>"+Teacher2(Exam2.score2).showStudentExamInfo())
        Log.d(KtBaseSealedTest01_TAG, "testSealed01==>"+Teacher2(Exam2.score3).showStudentExamInfo())
        Log.d(KtBaseSealedTest01_TAG, "testSealed01==>"+Teacher2(Exam2.score4("马云")).showStudentExamInfo())
    }
}

相关文章

网友评论

      本文标题:kotlin 密封类sealed class

      本文链接:https://www.haomeiwen.com/subject/ifoazrtx.html