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
Jiddles
06/09/2021, 2:05 PM
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
Zach Klippenstein (he/him) [MOD]
06/09/2021, 3:34 PM
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
Vivek Modi
06/09/2021, 3:49 PM
@Zach Klippenstein (he/him) [MOD] okk i got it what you mean thanks for your help 😁