【问题标题】:Is it necessary to check null when use 'is' operator使用'is'运算符时是否需要检查null
【发布时间】:2021-01-18 10:51:53
【问题描述】:

我有一个可以为空的实例。狐狸例子

var str: String? = null

所以我需要检查 str 是否为字符串。如果我使用 is 运算符,是否需要检查 null。 第一个选项:

if(str is String) {}

第二个选项:

if(str != null && str is String) {} 

请帮助我使用哪种方式更好?

【问题讨论】:

    标签: kotlin typechecking


    【解决方案1】:

    is 运算符是安全的,在您提供空实例的情况下返回 false

    https://pl.kotl.in/HIECwc4Av

    在某个地方,您必须进行空检查。 Kotlin 提供了许多方法来强制非空:

    使用非空类型:

    var nonNull : String = ""
    var nullable : String? = "" // notice the ?
    
    nullable = null // works fine!
    nonNull = null // compiler error
    

    如果您遇到可空类型,您可以使用let {} ?: run {} 构造将其解包并使用不可空类型执行您的代码:

    nullable?.let { // use "it" to access the now non-null value
        print(it)
    } ?: run { // else
        print("I am null! Big Sad!")
    }
    

    Kotlin 严格区分可空的 T? 和不可空的 T。 尽可能使用T 以避免空检查。

    【讨论】:

    • 是的,但是否值得检查 null 以避免进行不必要的类型检查?
    • @testovtest, is 运算符转换为 INSTANCEOF 字节码操作,它也检查 null。在使用 is 之前检查 null 并没有真正的好处。
    猜你喜欢
    • 2012-11-21
    • 2013-05-12
    • 2015-01-15
    • 1970-01-01
    • 2016-06-25
    • 2013-02-06
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    相关资源
    最近更新 更多