0

I'm trying to understand what is happening inside of the LazyColumn with the interface LazyListScope and its extension function items(List<T>,...).

The concept was new to me and I was playing around a little bit with the program.

Now, I wonder - why is this code not printing the message from the extension function?

If I'm right the method printInterface() is implementing MyInterface via an anonymous object. The extension function of the interface should work now, or not? But if I run the program I don't see the message "Hello" from the extension function.

fun main(args: Array<String>){
    printInterface {
        printExtension()
    }
}

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

interface MyInterface {}

fun MyInterface.printExtension() {
    println("Hello")
}

ardiien
  • 767
  • 6
  • 26
steeveKA1
  • 13
  • 6

1 Answers1

1

You need to have an instance and call it to trigger the print

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

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

interface MyInterface
class MyClass : MyInterface

fun MyInterface.printExtension() {
    println("Hello")
}
ardiien
  • 767
  • 6
  • 26
  • Hey thank you for the answer. But i still dont understand. If i call printInterface() in main it shows, this:MyInterface, so an object of MyInterface was already anonymously created by the compiler. Why should the param content need an implementation of MyInterface in a class? Somehow i dont get it. Why can i not just write content()? If i look at Jetpack Compose there is no LazyListScope implemented anywhere... and the content of the items() extension function from the LazyListScope-Interface is never used in the method body?! – steeveKA1 Jul 31 '23 at 13:21
  • 1
    How would the compiler know how to implement `MyInterface`? It could be just any arbitrary interface. In the above case the compiler converts the provided lambda into a function that acts on `MyInterface`. It doesn't provide the implementation of `MyInterface` itself. Usually, `printInterface()` has to provide such implementation. – broot Jul 31 '23 at 16:48
  • @steeveKA1 You can read more about lambda with receivers [here](https://kotlinlang.org/docs/lambdas.html#function-literals-with-receiver), they've explained it pretty good there. Also, check their example for `html` function. – ardiien Aug 01 '23 at 12:58
  • The `LazyListScope` is built with a combination of extension functions and lambda with receivers (inline functions as well). That's why it feels like there is no instantiation involved. As you may see they have implementation for `LazyListScope` - `LazyListScopeImpl`. – ardiien Aug 01 '23 at 15:42