Hey i want to add items in array list using getter...
# android
v
Hey i want to add items in array list using getter in kotlin. Can someone explain what i am doing wrong here.
Copy code
private var categoryType = arrayListOf<CategoryType>()
    get() {
        if (category1List != null) {
            field = arrayListOf(CategoryType.Category1)
        }

        if (category2List != null) {
            field = arrayListOf(CategoryType.Category2)
        }

        if (category3List != null) {
            field = arrayListOf(CategoryType.Category3)
        }
        return field
    }
enum class CategoryType(val valueName: String) {
    ALL("ALL"),
    Category1("Category1"),
    Category2("Category2"),
    Category3("Category3");

    companion object {
        fun getArray(): List<CategoryType> {
            return values().map {
                it
            }
        }
    }
}
j
I think you might need to provide some more context with this example. Could you maybe give us examples of it being populated? Where do
category1List
,
category2List
and
category3List
come from?
z
What unexpected behavior are you seeing? From the code you posted, it looks like that var should just be a val since you’re never reading the backing field. Also I am surprised that you can even write to the backing field from a getter - I’ve never seen that before. If that is really what you need to do though, it’s probably a hint that a property is not the best option for your API.
v
@Zach Klippenstein (he/him) [MOD] okk i got it what you mean thanks for your help 😁