Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Moosphan opened this issue Dec 2, 2019 · 7 comments
Open

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

Moosphan opened this issue Dec 2, 2019 · 7 comments
Labels

Comments

@Moosphan
Copy link
Owner

Moosphan commented Dec 2, 2019

No description provided.

@Moosphan Moosphan added the Kotlin label Dec 2, 2019
@Jsondx
Copy link

Jsondx commented Dec 2, 2019

a?.let{

}

@gabyallen
Copy link

not know

@cyixlq
Copy link

cyixlq commented Dec 2, 2019

对于方法传入的参数直接通过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
    }
}

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

@fansangg
Copy link

对于方法传入的参数直接通过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

@feelschaotic
Copy link

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

@Krosxx
Copy link

Krosxx commented Jun 8, 2020

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

@lyx0224
Copy link

lyx0224 commented Jan 10, 2024

对于方法传入的参数直接通过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)
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

8 participants