Joshua Hansen
01/09/2024, 11:31 PMList
via delegation. I set up a property delegate function to add to the list whenever a property is defined in the class. This is just a way for me to iterate through properties of a class. The class itself uses a map as the "backing field" data structure (for lack of a better term)
class ListItem<T>(
val itemName: String,
val getValue: () -> T,
)
class MyList(private val list: MutableList<ListItem<*>>) : List<ListItem<*>> by list {
constructor() : this(mutableListOf())
private val map: Map<String, Any> = mapOf(
"item1" to 1,
"item2" to "2",
)
val item1: Int by listItem()
val item2: String by listItem()
private fun <T> listItem() = PropertyDelegateProvider { thisRef: MyList, prop ->
val item = ListItem(prop.name) {
thisRef.map[prop.name]!! as T // Unchecked cast
}
thisRef.list.add(item)
ReadOnlyProperty { _: MyList, _ -> item }
}
}
With this, I should be able to do
val myList = MyList()
myList.forEach { println("${it.name} ${it.getValue()}") }
but also this
myList.item1
myList.item2
I'm getting an unhelpful error message when declaring the properties in the class body:
Property delegate must have a 'getValue(MyList, KProperty*>)' method. None of the following functions are suitable.
- getValue(MyList, KProperty<*>) defined in kotlin.properties.ReadOnlyProperty
Any idea what's going on?Joshua Hansen
01/09/2024, 11:37 PMval item1 by listItem<Int>()
val item2 by listItem<String>()
Not sure why thoughJoshua Hansen
01/09/2024, 11:41 PMReadOnlyProperty
. I needed to specify it as the type parameter for the function itself.Adam S
01/09/2024, 11:43 PMReadOnlyProperty { _: MyList, _ -> item }
with
ReadOnlyProperty { _: MyList, _ -> item.getValue() }
makes the red go awayJoshua Hansen
01/09/2024, 11:45 PMReadOnlyProperty<ListItem<T>>
but by specifying the type at the property declaration, I was asking for ReadOnlyProperty<T>
mkrussel
01/10/2024, 1:32 PM