简体   繁体   English

kotlin 中的条件可空返回类型

[英]Conditional nullable return type in kotlin

I wrote some code and that work!我写了一些代码,而且工作正常!

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

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

but when i converted it to extention function dosent work.但是当我将它转换为扩展功能时,它不起作用。 compiler say method name is duplicated.编译器说方法名称重复。

I need somthing like this :我需要这样的东西:

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

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

or is there annotation to say if input parameter is null return type is null too ?或者是否有注释说明输入参数是否为空,返回类型是否也为空?

By the looks of it, your objective can be accomplished with safe calls.从表面上看,您的目标可以通过安全调用来实现。 Say you had this function:假设你有这个功能:

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

You can use it on a nullable long like so:您可以在可空的 long 上使用它,如下所示:

myNullableLong?.toDate()

That will return null if the long is null, and the correct date otherwise.如果 long 为 null,则返回 null,否则返回正确的日期。

The problem is that you'll have to think about how this looks in the JVM when using kotlin for the JVM.问题在于,在 JVM 中使用 kotlin 时,您必须考虑这在 JVM 中的外观。 Your methods:你的方法:

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

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

Are equivalent in Java to:在 Java 中相当于:

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

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

Unfortunately, in Java annotations do nothing to resolve ambiguity of declarations (neither return types), so essentially these methods are the same and that's why the compiler complains.不幸的是,在 Java 中,注解并不能解决声明的歧义(无论是返回类型),所以本质上这些方法是相同的,这就是编译器抱怨的原因。

Like some already mentioned, you most likely can just use safe calls.就像已经提到的一些一样,您很可能只能使用安全调用。

Declare an extension on Long and whenever this long can be null, just call ?.toDate on it.Long上声明一个扩展,只要这个 long 可以为空,就调用?.toDate就可以了。 Just like @llama Boy suggested.就像@llama Boy 建议的那样。

This will achieve what you want:这将实现您想要的:

  1. When input is nullable, output will be nullable too当输入可以为空时,输出也可以为空
  2. When input is not nullable, output will be not nullable too.当输入不可为空时,输出也不可为空。

You can avoid the problem by using @JvmName annotation on one of them :您可以通过在其中之一上使用@JvmName注释来避免该问题:

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

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

but I agree with the other answers that in most cases you can prefer just using safe calls instead of defining a separate Long?.toDate .但我同意其他答案,在大多数情况下,您可以更喜欢只使用安全调用而不是定义单独的Long?.toDate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM