Kotlin教程:可空null和非可空类型

2020-04-2020:54:32编程语言入门到精通Comments1,503 views字数 1407阅读模式

Kotlin null安全性是一种消除代码中空引用风险的过程。 如果Kotlin编译器发现任何null参数而仍然执行null引用相关语句,则会立即抛出NullPointerException文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

Kotlin的类型系统旨在消除代码中的NullPointerExceptionNullPointerException只能用于以下原因:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

  • 强行调用抛出NullPointerException;
  • 未初始化此运算符,可在构造函数中传递并在某处使用。
  • 使用外部Java代码作为Kotlin,是Kotlin与Java互操作性。

Kotlin可空类型和非可空类型

Kotlin类型系统区分可以保持null(可空引用)和不能保持null(非null引用)的引用。 通常,String类型不可为null。 要创建保存null值的字符串,必须通过放置一个?来明确定义它们。 例如,在String后面使用:String?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

可空类型

通过放置一个?来声明可空类型? 在String后面:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

var str1: String? = "hello"  
str1 = null // ok
Kotlin

Kotlin可空类型的例子文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

fun main(args: Array<String>){  
    var str: String? = "Hello" // 变量被声明为可空
    str = null  
    print(str)  
}
Kotlin

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

null
Shell

非可空类型

非可空类型是普通字符串,它们声明为String类型:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

val str: String = null // compile error  
str = "hello" // compile error Val cannot be reassign  
var str2: String = "hello"  
str2 = null // compile error
Kotlin

null值赋给非可空字符串时会发生什么?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

fun main(args: Array<String>){  
    var str: String = "Hello"  
    str = null // compile error  
    print(str)  
}
Kotlin

它将生成编译时错误,如下所示 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

Error:(3, 11) Kotlin: Null can not be a value of a non-null type String
Shell

在条件中检查null

Kotlin的if表达式用于检查条件并返回值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18275.html

fun main(args: Array<String>){
    var str: String? = "Hello"     // variable is declared as nullable
    var len = if(str!=null) str.length else -1
    println("str is : $str")
    println("str length is : $len")

    str = null
    println("str is : $str")
    len = if(str!=null) str.length else -1
    println("b length is : $len")
}
Kotlin

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

str is : Hello
str length is : 5
str is : null
b length is : -1

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

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

Comment

匿名网友 填写信息

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

确定