【问题标题】:why the methods /propreties of an interface can be passed in an extension function为什么接口的方法/属性可以在扩展函数中传递
【发布时间】: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


【解决方案1】:

在扩展函数的范围内,您有一个其扩展类型的实例(在您的示例中为FruitColorsInterface),可用作this — 一个隐式接收器。

使用 this 实例,您可以调用该类型上可用的其他函数和属性,无论它们是成员还是扩展。

为什么在扩展函数体中可以只调用mixColors()而不是this.mixColors(),这是因为this是隐式可用的,与成员函数体中一样,因此可以省略。

【讨论】:

  • 有时语法糖让我与旧的java逻辑失去联系,但我原谅kotlin,它务实又快速,如果想理解我总能看到生成的java代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 2012-11-06
  • 2014-09-03
  • 1970-01-01
  • 2011-02-15
相关资源
最近更新 更多