Anil
Anil

Reputation: 265

Best practice to access property in kotlin

I comes from Java background and working first time on Kotlin. For most of the people it will be basic question, but it may help people who start working first time on Kotlin and comes from Java background

So, let say I have listadapter and I want to set list of item in that. I have two options now.

1) create a private property which stores list of items and then create a setter for it, which set the list and call notifydatasetChanged()

2) create a property with set property function and then access like instance.property

Which will be better option in Kotlin out of above two options.

Upvotes: 0

Views: 490

Answers (1)

tynn
tynn

Reputation: 39853

A property in Kotlin is nothing else then a getter and setter for a value. If you don't want to provide a getter, you have to use a fun setData(data: List).

Otherwise it's also possible to handle everything with the property

var data = listOf()
        set(data: List) {
            field = data
            notifydatasetChanged()
        }

But eventually it's even better to use an implementation with DiffUtil.

Upvotes: 1

Related Questions