我想创建一个类似于Kotlin的ifEmpty()的函数,该函数还将判断null:

ifNullOrEmpty{
  //some code if null or empty
}

我该怎么做?

有人知道下面的代码叫什么吗?

: R where C : CharSequence, C : R

Kotlin ifEmpty()函数的示例.

@SinceKotlin("1.3")
@kotlin.internal.InlineOnly
public inline fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : CharSequence, C : R =
    if (isEmpty()) defaultValue() else this

谢谢,祝你今天愉快!

推荐答案

正如在其他答案中所解释的那样,您无法使用与ifNull()中类似的泛型逻辑创建ifNullOrEmpty(),因为您需要@InlineOnly,它当前是内部的,只能由stdlib使用.

如果您不介意使用内部组件和编写可能不向前兼容的代码,您可以利用一个小技巧:

@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
@kotlin.internal.InlineOnly
public inline fun <C, R> C.ifNullOrEmpty(defaultValue: () -> R): R where C : CharSequence, C : R =
    if (isNullOrEmpty()) defaultValue() else this

或者,您可以使用@Joffrey提供的"不那么通用"的实现,这对于大多数用例来说应该足够了.

Kotlin相关问答推荐

如何在 Big Data 中使用Inc过滤器?

如何将时间值格式化为00:00和00:00:00 Kotlin?""""

Kotlin 获取继承类的默认 hashCode 实现

将一个列表元素分组为多个组(indexBy)

区分函数和扩展

关于 Kotlin 函数类型转换的问题

伴随对象在变量更改时更改它的值

Kotlin RxJava 可空的错误

为什么 android studio 不为所有安全参数生成代码?

Kotlin:泛型、反射以及类型 T 和 T:Any 之间的区别

Gradle 同步失败:不支持的方法:KotlinPlatformContainer.supports()

Kotlin Compose,在行中对齐元素

Android Room - error: Cannot figure out how to save this field into database

Kotlin协程处理错误和实现

Kotlin 的 Double.toInt() 中使用了哪种方法,舍入还是截断?

如何在Kotlin中使用ViewModelProviders

TypeConverter()在Android的TypeConverter错误中具有私有访问权限

IllegalStateException:function = , count = 3, index = 3

从 Kotlin 访问 Integer.class

如何在 Kotlin 中将串联转换为模板