kotlin 中的条件可为空 return 类型

Conditional nullable return type in kotlin

我写了一些代码,效果很好!

    public fun toTimeStamp(epoch: Long?): String? = when (epoch) {
        null -> null
        else -> toTimeStamp(epoch)
    }

    public fun toTimeStamp(epoch: Long): String = 
        TIMESTAMP_PATTERN.print(toGregorianDateTime(epoch))

但是当我将它转换为扩展函数时,它起作用了。 编译器说方法名称重复。

我需要这样的东西:

fun Long?.toDate() : String? {
// some code
}

fun Long.toDate() : String {
// some code
}

或者是否有注释说明输入参数是否为空 return 类型也为空?

看起来,您的 objective 可以通过安全调用来完成。 假设你有这个功能:

fun Long.toDate(): String =
    TIMESTAMP_PATTERN.print(toGregorianDateTime(epoch))

您可以像这样在可为 null 的 long 上使用它:

myNullableLong?.toDate()

如果 long 为空,则 return 为空,否则为正确的日期。

问题是,在将 kotlin 用于 JVM 时,您必须考虑这在 JVM 中的外观。你的方法:

fun Long?.toDate() : String? {
   // some code
 }

fun Long.toDate() : String {
   // some code
}

在 Java 中等同于:

public static @Nullable String toDate(@Nullable Long receiver) {}

public static @NonNull String toDate(long receiver) {}

不幸的是,在 Java 中,注释无法解决声明的歧义(return 类型),因此这些方法本质上是相同的,这就是编译器抱怨的原因。

就像已经提到的那样,您很可能只使用安全调用。

Long 上声明一个扩展,只要这个 long 可以为 null,就在其上调用 ?.toDate。就像@llama Boy 建议的那样。

这将实现你想要的:

  1. 当输入可以为空时,输出也可以为空
  2. 当输入不可为空时,输出也不可为空。

你可以避免这个问题by using @JvmName annotation on one of them:

@JvmName("toDateNullable")
fun Long?.toDate() : String? {
// some code
}

fun Long.toDate() : String {
// some code
}

但我同意其他答案,在大多数情况下你可以更喜欢只使用安全调用而不是定义单独的 Long?.toDate