y-tomimoto
y-tomimoto

Reputation: 13

What does "val XXX = Class { ... " mean in Kotlin?

In Kotlin, what does this syntax mean ?

class HomeActivity : AppCompatActivity() {
    val examplesAdapter =  HomeOptionsAdapter {
        val fragment = it.createView()
        ...
    }

https://github.com/kizitonwose/CalendarView/blob/6be23be1f721fe2e08e5f2e2e7f29ad0b519c327/sample/src/main/java/com/kizitonwose/calendarviewsample/HomeActivity.kt#L15

I just thought Anonymous function or Lambdas ...

Upvotes: 1

Views: 442

Answers (1)

Francesc
Francesc

Reputation: 29260

I you check the HomeOptionsAdapter you'll see in the constructor this

class HomeOptionsAdapter(val onClick: (ExampleItem) -> Unit) 

so it takes an onClick listener, a function that takes a ExampleItem as input and returns Unit. This is a Kotlin language feature, you can place a lambda outside the () if it's the last parameter. These are equivalent:

val examplesAdapter =  HomeOptionsAdapter({
    val fragment = it.createView()
    ...
})

val examplesAdapter =  HomeOptionsAdapter {
    val fragment = it.createView()
    ...
}

Upvotes: 3

Related Questions