Home > Mobile >  how to make kotlin interface property with default value to be used in java code
how to make kotlin interface property with default value to be used in java code

Time:10-09

Using kotlin 1.6.21, and java 11. Having a kotlin interface which has property with default value. How to make use it in java code?

interface ISomeKInterface {
   val flag: Int
       get() = return 1

   fun onProc(data: Data) {
       if (flag == 1) {
          // do something_1
       } else if (flag == 2) {
          // do something_2
       } else {
          // do the other
       }
   }
}

in kotlin it could do

object : ISomeKInterface {
    override val flag: Int = 2
    override fun onProc(data: Data) {
       if (flag == 1) {
          // do something_1
       } else if (flag == 2) {
          // do different implementation for flag 2
       } else {
          // do the other
       }
   }
}

CodePudding user response:

I use kotlin interface in java , so easy

   public class Test {
    public static void main(String[] args) {
        ISomeKInterface iSomeKInterface = new ISomeKInterface() {
            @Override
            public void onProc() {
            }

            @Override
            public int getFlag() {
                return 2;
            }
        };
        System.out.println(iSomeKInterface.getFlag());
    }
}

CodePudding user response:

Actually, the code override val flag: Int = 2 not change the flag value in ISomeKInterface ,and you can use super.flag get the the value which is 1.

further on,kotlin generate get,set function automatic, so if you want use in java, u need change the getFlag() function:

  ISomeKInterface anInterface = new ISomeKInterface() {
    @Override
    public void onProc(@NonNull Object data) {

    }

    @Override
    public int getFlag() {
        return 2;
    }
};

CodePudding user response:

Default Method in Java 8:

public interface Alarm {

    default String turnAlarmOn() {
        return "Turning the alarm on.";
    }
    
    default String turnAlarmOff() {
        return "Turning the alarm off.";
    }
}

Reference: https://www.baeldung.com/java-static-default-methods

  • Related