Kotlingenerics改变返回types
我在Java中有这种方法我想转换为Kotlin,但仍然使用Java和Kotlin:
@Nullable public static T nullIfEmpty(@Nullable final T t) { return TextUtils.isEmpty(t) ? null : t; }
在另一个地方,我有一个接受字符串的方法:
public static doSomething(@Nullable String foo) {}
我这样叫:
String foo = ""; doSomething(nullIfEmpty(foo)); // == doSomething(null); since foo is empty
在将nullIfEmpty()
转换为这个Kotlin代码片段之后:
fun nullIfEmpty(t: T?): T? { return if (TextUtils.isEmpty(t)) null else t }
Java不再编译抱怨有一个参数types不匹配 – 当它期望一个String
时用CharSequence
调用该函数。
什么是正确的语法来解决这个问题?
如果你使用的是Java 8(或者更高版本,我想),这个代码实际上就像你提交的那样工作。
在较早的版本中(我假设你在Android上),输入推断比较弱,你必须明确地指定通用types才能工作,就像这样:
String foo = " "; doSomething(K.nullIfEmpty(foo));
(我已经将Kotlin函数包装在一个名为K
的对象中,我用这个限定符调用它,以便可以将types参数放在Java调用站点。我不认为你可以提供静态types参数import。)
附注:请注意,这是TextUtils.isEmpty()
的实现,因此它不会像" "
那样返回true
。
/** * 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; }