从 java 调用带有密封 class 参数的 Kotlin 函数
Calling Kotlin function with parameter as sealed class from java
我的 Kotlin class TimeUtils
有一个密封的 class 声明为:
sealed class TimeUnit {
object Second : TimeUnit()
object Minute : TimeUnit()
fun setTimeOut(timeout : TimeUnit) {
// TODO something
}
我的 Java class 正在调用 setTimeOut
方法,例如:
TimeUtils obj = new TimeUtils();
if (some condition) {
obj.setTimeOut(TimeUtils.TimeUnit.Minute); // ERROR
} else if (some other condition) {
obj.setTimeOut(TimeUtils.TimeUnit.Second); // ERROR
}
我在以上 2 行中收到错误 expression required
。
谁能帮我解决一下?
您应该按如下方式调用函数:
obj.setTimeOut(TimeUtils.TimeUnit.Minute.INSTANCE);
因为object Minute
会被编译成下面的Java代码:
public final class Minute {
public static final Minute INSTANCE;
private Minute() {
}
static {
Minute var0 = new Minute();
INSTANCE = var0;
}
}
我的 Kotlin class TimeUtils
有一个密封的 class 声明为:
sealed class TimeUnit {
object Second : TimeUnit()
object Minute : TimeUnit()
fun setTimeOut(timeout : TimeUnit) {
// TODO something
}
我的 Java class 正在调用 setTimeOut
方法,例如:
TimeUtils obj = new TimeUtils();
if (some condition) {
obj.setTimeOut(TimeUtils.TimeUnit.Minute); // ERROR
} else if (some other condition) {
obj.setTimeOut(TimeUtils.TimeUnit.Second); // ERROR
}
我在以上 2 行中收到错误 expression required
。
谁能帮我解决一下?
您应该按如下方式调用函数:
obj.setTimeOut(TimeUtils.TimeUnit.Minute.INSTANCE);
因为object Minute
会被编译成下面的Java代码:
public final class Minute {
public static final Minute INSTANCE;
private Minute() {
}
static {
Minute var0 = new Minute();
INSTANCE = var0;
}
}