Search code examples
javakotlinsealed-class

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?


Solution

  • 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;
       }
    }