Android 为什么接口的方法/属性可以在扩展函数中传递
今天我不得不使用一个扩展函数,它作为一个接口的谓词,一种Android 为什么接口的方法/属性可以在扩展函数中传递,android,oop,kotlin,interface,extension-function,Android,Oop,Kotlin,Interface,Extension Function,今天我不得不使用一个扩展函数,它作为一个接口的谓词,一种接口。whateverExtensionFunction() 我有一个类ViewModel():interfaceinheritingfromanotherinterface。建筑理念 后面的任务是保持我的viewModel整洁,并将一些重要任务委托给扩展功能。 我不明白为什么我要将扩展函数FruitColorsInterface.changeColors()作为下面代码中的方法调用到我的ViewModel中cut() 我不理解如何才能有效
接口。whateverExtensionFunction()
我有一个类ViewModel():interfaceinheritingfromanotherinterface
。建筑理念
后面的任务是保持我的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.mixColors()
,这是因为this
与成员函数体中一样隐式可用,因此可以忽略它 扩展函数接受任何实现水果色接口的具体对象。然后它对该对象调用mixColors()
,并将执行在该对象内部实现的具体方法。在您的例子中,通过调用扩展函数,您传递了这个
:它是AppleTrimViewModel
的一个实例,它确实实现了mixColors()
。有时语法糖会让我与旧的java逻辑失去联系,但我原谅kotlin,实用且快速,如果想理解,我可以随时看到生成的java代码