Skip to content

2019-12-02:Kotlin中该如何安全地处理可空类型? #201

Open

Description

@Moosphan
No description provided.

Activity

  1. Jsondx commented on Dec 2, 2019

    @Jsondx

    a?.let{

    }

  2. gabyallen commented on Dec 2, 2019

    @gabyallen

    not know

  3. cyixlq commented on Dec 2, 2019

    @cyixlq

    对于方法传入的参数直接通过if判断,例如:

    fun a(tag: String?, type: String) {
        if (tag != null && type != null){
            // do something
        }
    }
    

    还有就是

    a?.let{}
    a?.also{}
    a?.run{}
    a?.apply{}
    

    然后接着有一个疑问,假如同时判断两个变量,写成:

    a?.let{
        b?.let{
            //do something
        }
    }
    

    这样似乎有点不够优雅,想看看大家有什么优雅的写法

  4. fansangg commented on Dec 11, 2019

    @fansangg

    对于方法传入的参数直接通过if判断,例如:

    fun a(tag: String?, type: String) {
        if (tag != null && type != null){
            // do something
        }
    }
    

    还有就是

    a?.let{}
    a?.also{}
    a?.run{}
    a?.apply{}
    

    然后接着有一个疑问,假如同时判断两个变量,写成:

    a?.let{
        b?.let{
            //do something
        }
    }
    

    这样似乎有点不够优雅,想看看大家有什么优雅的写法

    takeif

  5. feelschaotic commented on Dec 24, 2019

    @feelschaotic

    补充一点,尽量不要出现空,也就不需要处理空,参考 Java 的空对象模式

  6. Krosxx commented on Jun 8, 2020

    @Krosxx

    另外注意在调用java方法时对返回值进行处理;最好在方法加上@nullable 或@NotNull 注解

  7. lyx0224 commented on Jan 10, 2024

    @lyx0224

    对于方法传入的参数直接通过if判断,例如:

    fun a(tag: String?, type: String) {
        if (tag != null && type != null){
            // do something
        }
    }
    

    还有就是

    a?.let{}
    a?.also{}
    a?.run{}
    a?.apply{}
    

    然后接着有一个疑问,假如同时判断两个变量,写成:

    a?.let{
        b?.let{
            //do something
        }
    }
    

    这样似乎有点不够优雅,想看看大家有什么优雅的写法

    takeif
    这样写比较优雅了

    fun <T1, T2> ifNotNull(value1: T1?, value2: T2?, bothNotNull: (T1, T2) -> (Unit)) {
    if (value1 != null && value2 != null) {
    bothNotNull(value1, value2)
    }
    }

  8. istudygithub commented on Sep 1, 2026

    @istudygithub

    Kotlin 将可空性纳入了类型系统,普通类型默认不可为空,只有通过 ? 声明的类型才允许为 null,这样可以在编译期发现很多空指针问题。

    对于可空类型,常见的处理方式主要有:

    if 判空,编译器会进行 Smart Cast;
    ?. 安全调用,对象为空时不会调用成员,而是返回 null;
    ?: Elvis 操作符,为空时提供默认值,也可以配合 return、throw 做提前退出;
    ?.let {},只在对象非空时执行代码块;
    as? 进行安全类型转换,转换失败返回 null;
    对集合可以使用 filterNotNull() 过滤空元素。

    !! 虽然可以强制将可空类型当成非空类型,但如果实际为 null 会抛出 NPE,所以实际开发中应该尽量避免使用。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions