在Kotlin中将两个可为null的Int相加的最易读的方法是什么? [英] What is the most readable way to sum two nullable Int in Kotlin?

查看:97
本文介绍了在Kotlin中将两个可为null的Int相加的最易读的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试执行以下操作:

val a: Int? = 1
val b: Int? = 1

a?.plus(b)

但它不能编译,原因是 plus 期望为 Int .

but it doesn't compile cause plus expects an Int.

我还试图创建一个biLet函数:

I also tried to create a biLet function:

fun <V1, V2, V3> biLet(a: V1?, b: V2?, block: (V1, V2) -> V3): V3? {
    return a?.let {
        b?.let { block(a, b) }
    }
}

并像这样使用它:

val result = biLet(a, b) { p1, p2 -> p1 + p2 }

但是似乎很简单的事情却需要很多工作.有没有更简单的解决方案?

but it seems a lot of work for something apparently simple. Is there any simpler solution?

推荐答案

不幸的是,标准库中没有任何东西可以求和两个可为null的整数.

Unfortunately there isn't anything already in the standard library to sum two nullable ints.

但是,您可以做的是为可为空的 Int创建一个 operator fun :

What you can do, however, is to create an operator fun for a nullable Int?:

operator fun Int?.plus(other: Int?): Int? = if (this != null && other != null) this + other else null

然后,您可以像非空版本一样正常使用它:

And then, you can use it normally like the not-null version:

val a: Int? = 2
val b: Int? = 3
val c = a + b

如果不想为其创建函数,则始终可以使用其主体来处理两个int的可为空性.

If you don't want to create a function for it, you can always use its body to handle the nullability of the two ints.

这篇关于在Kotlin中将两个可为null的Int相加的最易读的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆