Kotlin - 带有扩展功能的扩展接口,为什么不起作用?

问题描述 投票:0回答:1

我尝试通过接口 LazyListScope 及其扩展函数 items(List,...) 来了解 LazyColumn 内部发生了什么。 这个概念对我来说是新的,我正在尝试这个程序。现在我想知道这个: 为什么此代码不打印来自扩展函数的消息?如果我是对的,方法 printInterface() 正在通过匿名对象实现 MyInterface。接口的扩展功能现在应该可以用了,还是不行? 但如果我运行该程序,我不会从扩展功能中看到消息“Hello”。

  fun main(args: Array<String>){


  printInterface {
         printExtension()

           }

       }

  fun printInterface(content: MyInterface.() -> Unit){

       }

  interface MyInterface{

        }

  fun MyInterface.printExtension() {
            println("Hello")
        }
android kotlin interface extension-methods lazycolumn
1个回答
0
投票

您需要有一个实例并调用它来触发

print

fun main() {
    printInterface {
        printExtension()
    }
}

fun printInterface(content: MyInterface.() -> Unit){
    content(MyClass())
}

interface MyInterface
class MyClass : MyInterface

fun MyInterface.printExtension() {
    println("Hello")
}
© www.soinside.com 2019 - 2024. All rights reserved.