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: String) {
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: String) {
if (flag == 1) {
// do something_1
} else if (flag == 2) {
// do different implementation for flag 2
} else {
// do the other
}
}
}
Edit: in kotlin it works with either override the property or override the getter
fun test_() {
val theInterfaceImpl: ISomeKInterface = object : ISomeKInterface {
//override val flag: Int = 2
// the override the getter does the same as above override flag:Int = 2
override val flag: Int
get() {
val superFlag: Int = super.flag
println("+++ test override get(), flag:$superFlag, ret flag: 2")
return 2
}
// if no change to the default implementation this override is not required.
override fun onProc(data: String) {
println("+++ test override onProc(), flag: $flag default onProc(:$data)")
super.onProc(data)
}
}
val flag = theInterfaceImpl.flag
println("+++ test current flag:$flag")
theInterfaceImpl.onProc("eee888")
}
But it does not compile if trying to use it in java.
In java it requires the @Override public void onProc(String data), but it cannt call the super's default implementation - for the case that the default implementation of the ISomeKInterface is goog enough and does not need different implementation override.
@Test
public void test_() {
ISomeKInterface theInterfaceImpl = new ISomeKInterface() {
@Override
public int getFlag() {
// int superFlag = ISomeKInterface.super.getFlag(); //<== got error on ISomeKInterface.super.
// System.out.println("+++ flag:"+superFlag+", ret flag: "+2);
return 2;
}
@Override
public void onProc(@NonNull String data) {
// it is require the implement the onPro(data: String although it has the default implementation already)
// but what if the super's default onProc() works fine, and does not need provide different implementation??? it seems cannot call the super.onProc here
System.out.println("+++ test override onProc(:"+data);
ISomeKInterface.super.onProc(data); //<===
}
};
int flag = theInterfaceImpl.getFlag();
System.out.println("+++ current flag:"+flag);
theInterfaceImpl.onProc("eee888");
}
error: abstract method onProc(String) in ISomeKInterface cannot be accessed directly
ISomeKInterface.super.onProc(data); //<===
^
I use kotlin interface in java , so easy