Understanding a parameter that is initialized as an extension function

后端 未结 2 2024
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-10 11:03

In the following code the parameter type for modelInitializer is CalendarMonthTitleModelBuilder.()

What does the .() mean?. I believe the dot r

2条回答
  •  野性不改
    2021-02-10 11:30

    First of all ()->Unit is a lambda. And this lambda has a this, and it's type is the CalendarMonthTitleModelBuilder. It's called lambda with a receiver.

    So inside modelInitializer you can access to CalendarMonthTitleModelBuilder as you are inside this class: using this.

    For example, I assume that CalendarMonthTitleModelBuilder has a someMethod:

    val epoxyController: EpoxyController = EpoxyController()
    
    epoxyController.calendarMonthTitle {
        // inside these curlies `this: CalendarMonthTitleModelBuilder = CalendarMonthTitleModel_()`
        this.someMethod() //you can use 'this' inside this lambda
        someMethod() // or as usual just skip writing 'this', just access `CalendarMonthTitleModelBuilder` methods as you inside it's class
    
    }
    

    This feature is essential in building DSLs.

    Here is a link to documentation.

提交回复
热议问题