Kotlin教程:不安全和安全类型转换操作符

2020-04-2121:46:18编程语言入门到精通Comments1,657 views字数 1158阅读模式

不安全的转换操作符:as

有时无法转换变量并抛出异常,这称为不安全转换。 不安全的强制转换由中缀运算符执行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

可以为空的字符串(String?)不能转换为非null字符串(String),这会引发异常。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

un main(args: Array<String>){
    val obj: Any? = null
    val str: String = obj as String
    println(str)
}
Kotlin

以上程序抛出异常:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

Exception in thread "main" kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String  
 at TestKt.main(Test.kt:3)
Shell

尝试将Any类型的整数值转换为字符串类型导致生成ClassCastException文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

val obj: Any = 123  
val str: String = obj as String   
// Throws java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
Kotlin

源和目标变量需要可以为转换工作:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

fun main(args: Array<String>){
    val obj: String? = "String unsafe cast"
    val str: String? = obj as String? // Works  
    println(str)
}
Kotlin

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

String unsafe cast
Shell

Kotlin安全转换操作符:as?

Kotlin提供安全转换操作符:as?安全地转换成一种类型。 如果无法进行转换,则返回null,而不是抛出ClassCastException异常。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

让我们看一个例子,尝试转换任何类型的字符串值,程序员最初不知道编译器为可null string类型和可nullint类型。 如果可能的话,它会抛出值,或者返回null而不是抛出异常,甚至无法进行强制转换。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

fun main(args: Array<String>){

    val location: Any = "Kotlin"
    val safeString: String? = location as? String
    val safeInt: Int? = location as? Int
    println(safeString)
    println(safeInt)
}
Kotlin

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

Kotlin
null

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-unsafe-and-safe-cast-operator.html#article-start文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18277.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/18277.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定