【发布时间】:2020-03-23 11:47:19
【问题描述】:
今天我不得不使用一个扩展函数,它有一个接口作为谓词,一种Interface.whateverExtensionFunction()
我有一个class ViewModel () :InterfaceInherithingFromAnotherInterface。建筑理念
后面是保持我的 viewModel 整洁并将一些重量级委托给扩展功能。
我不明白为什么在我可以调用扩展函数 FruitColorsInterface.changeColors() 的任何方法中进入我的 ViewModel,如下面的代码中的方法 cut()
我不明白怎么可能有效地插入扩展函数,我可以调用接口方法
如果一个类实现了一个接口,这就是实现接口的方法而不是过多传递一个对象接口已经发生在这个扩展类中**
class testInterface(){
@Test
fun testInterface(){
AppleTrim().cut()
}
}
class AppleTrimViewModel : FruitColorsInterface{
override val red: String
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override val green: String
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override fun mixColors(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun move3d() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun spinFromTop(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun cut(){
changeColors()
//FruitColorsInterface.changeColors()//why this is error?
}
}
interface FruitColorsInterface {
val red :String
val green:String
fun mixColors(): String
fun move3d()
fun spinFromTop() :Int
}
fun FruitColorsInterface.changeColors(){
println("Ehy")
mixColors()//WHY IS THAT?
}
如果我在 Java 中反编译,我会得到一个传递接口的静态函数
public static final void changeColors(@NotNull FruitColorsInterface $this$changeColors) {
Intrinsics.checkParameterIsNotNull($this$changeColors, "$this$changeColors");
String var1 = "Ehy";
System.out.println(var1);
$this$changeColors.mixColors();
}
//and
public final void cut() {
Test_interfaceKt.changeColors(this);
}
【问题讨论】:
-
扩展函数接受任何实现
FruitColorsInterface的具体对象。然后它在该对象上调用mixColors(),它将执行在对象内部实现的具体方法。在您的情况下,通过调用扩展函数,您传递了this:它是AppleTrimViewModel的一个实例,它确实实现了mixColors()。
标签: android oop kotlin interface extension-function