简体   繁体   中英

Calling Kotlin function with parameter as sealed class from java

My Kotlin class TimeUtils has a sealed class declared as:

sealed class TimeUnit {
    object Second : TimeUnit()
    object Minute : TimeUnit()

fun setTimeOut(timeout : TimeUnit) {
    // TODO something
}

My Java class is calling setTimeOut method like:

TimeUtils obj = new TimeUtils();
if (some condition) {
    obj.setTimeOut(TimeUtils.TimeUnit.Minute);   // ERROR
} else if (some other condition) {
    obj.setTimeOut(TimeUtils.TimeUnit.Second);   // ERROR
}

I am getting error at above 2 lines stating expression required . Can anyone help how can I solve it?

You should invoke the function as following:

obj.setTimeOut(TimeUtils.TimeUnit.Minute.INSTANCE);

It's because object Minute will be compiled to the following Java code:

public final class Minute {
   public static final Minute INSTANCE;

   private Minute() {
   }

   static {
      Minute var0 = new Minute();
      INSTANCE = var0;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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