kotlin: 用 as 运算符进行类型转换

一,功能

as作用‌:将对象显式转换为目标类型。若类型不匹配,抛出 ClassCastException

 as?作用: 若转换失败,返回 null 而不是抛出异常

说明:
子类对象 声明为 父类类型 , 如果要 调用 子类 特有的方法 , 必须 使用 as 运算符进行 类型转换 ;

智能类型转换 : 
使用 as 运算符进行 类型转换 , 只要进行一次类型转换 ,
在后面还要调用子类成员时就可以直接调用 , 不再需要手动转换类型 ;

二,例子

代码:

        //处理按钮点击事件:
        binding.button3.setOnClickListener {
            open class Person(val name: String, val age: Int) {
                fun info() {
                    println("name : $name, age : $age")
                }

                open fun sayHello(){
                    println("Hello World")
                }
            }

            class Student : Person("Tom", 18){
                override fun sayHello(){
                    println("Hello World Tom")
                }

                fun helloStudent(){
                    println("Hello Student")
                }
            }

            var student: Person = Student()

            println("student is Person : ${student is Person}")
            println("student is Student : ${student is Student}")
            //创建 Student 对象 , 但是将其声明为 Person 类型 ,
            // 此时该对象只能调用 父类 Person 的成员 , 不能调用 Student 对象的特有成员
            student.sayHello()

            //student.helloStudent() //此处报错

            //将 student 对象转为 Student 类型 ,
            // 即可调用 Student 类中的 helloStudent 成员函数
            (student as Student).helloStudent()
            //在进行第一次转换之后 , 后面 student 对象 可以直接调用 helloStudent 函数 ,
            // 不再需要进行先转换类型再调用 , 这就是 智能类型转换
            student.helloStudent()
        }

运行结果:

image

三,例子

代码:

        //处理按钮点击事件
        binding.button4.setOnClickListener {
            //显式转换时如果不确定类型要做异常处理
            try {
                val num: Int = "ABC" as Int // 抛出 ClassCastException
            } catch (e: ClassCastException) {
                println("类型转换失败")
            }

            val num2: Int? = "ABC" as? Int
            println("num2的值:"+num2)
        }

运行结果:

image

posted @ 2025-09-06 08:38  刘宏缔的架构森林  阅读(19)  评论(0)    收藏  举报