Generics Kotlin泛型更改返回类型

Generics Kotlin泛型更改返回类型,generics,kotlin,nullable,Generics,Kotlin,Nullable,我在Java中有这个方法,我想转换成Kotlin,但仍然使用Java和Kotlin: @Nullable public static <T extends CharSequence> T nullIfEmpty(@Nullable final T t) { return TextUtils.isEmpty(t) ? null : t; } 我这样称呼它: String foo = ""; doSomething(nullIfEmpty(foo)); // == doSomet

我在Java中有这个方法,我想转换成Kotlin,但仍然使用Java和Kotlin:

@Nullable
public static <T extends CharSequence> T nullIfEmpty(@Nullable final T t) {
   return TextUtils.isEmpty(t) ? null : t;
}
我这样称呼它:

String foo = "";
doSomething(nullIfEmpty(foo)); // == doSomething(null); since foo is empty
在我将
nullIfEmpty()
转换为这个Kotlin代码段之后:

fun <T : CharSequence> nullIfEmpty(t: T?): T? {
    return if (TextUtils.isEmpty(t)) null else t
}
fun nullIfEmpty(t:t?):t?{
返回if(TextUtils.isEmpty(t))null else t
}
Java不再编译时抱怨参数类型不匹配——当它需要
字符串时,用
CharSequence
调用函数

/**
 * Returns true if the string is null or 0-length.
 * @param str the string to be examined
 * @return true if str is null or zero length
 */
public static boolean isEmpty(@Nullable CharSequence str) {
    return str == null || str.length() == 0;
}
解决这个问题的正确语法是什么?

如果您使用的是Java 8(或者更高版本,我想),那么这段代码实际上会按照您介绍的方式工作

在早期版本上(我假设您使用的是Android?),类型推断较弱,您必须显式指定泛型类型才能工作,如下所示:

String foo = "   ";
doSomething(K.<String>nullIfEmpty(foo));
如果您使用的是Java8(我想是更高版本),那么这段代码实际上将按照您所介绍的方式工作

在早期版本上(我假设您使用的是Android?),类型推断较弱,您必须显式指定泛型类型才能工作,如下所示:

String foo = "   ";
doSomething(K.<String>nullIfEmpty(foo));

顺便说一句,您可以按如下方式重写
nullIfEmpty
函数:
fun nullIfEmpty(t:t?):t?=t、 take除非{it.isNullOrEmpty()}
Btw,否则您可以将
nullIfEmpty
函数重写如下:
fun nullIfEmpty(t:t?):t?=t、 takeuncer{it.isNullOrEmpty()}
谢谢!这是不幸的,从Java7调用该方法会更加冗长,但我想我们可以更新到Java8(只是尝试了一下,它就工作了)。我还修复了我的示例-不知道为什么我写的是空字符串,而我的意思是空字符串。谢谢!这是不幸的,从Java7调用该方法会更加冗长,但我想我们可以更新到Java8(只是尝试了一下,它就工作了)。我还修复了我的示例-不知道为什么我写的是空字符串,而我的意思是空字符串。