Rob Elliot
01/31/2023, 2:00 PMclass User(map: MutableMap<String, Any> = mutableMapOf()): Map<String, Any> by map {
val name: String = "Joe" by map
val age: Int = 3 by map
}
val user = User()
user.toMap() == mapOf("name" to "Joe", "age" to 3)
user.name == "Joe"
user.age == 3
name
or age
key / property names.Sam
01/31/2023, 2:11 PMclass User(map: MutableMap<String, String>): Map<String, Any> by map {
var name: String by map
private set
init {
name = "Joe"
}
}
Rob Elliot
01/31/2023, 2:12 PMSam
01/31/2023, 2:14 PMclass User(map: MutableMap<String, Any>) : Map<String, Any> by map {
val name: String by map withInitialValue "Joe"
}
infix fun <V> MutableMap<String, V>.withInitialValue(initialValue: V) =
PropertyDelegateProvider<Any, Map<String, V>> { _, property ->
apply { put(property.name, initialValue) }
}
edit: omg it can be an infix function tooRob Elliot
01/31/2023, 2:27 PMclass User(map: MutableMap<String, Any>) : Map<String, Any> by map {
val name: String by map("Joe")
}
operator fun <V> MutableMap<String, V>.invoke(initialValue: V) =
PropertyDelegateProvider<Any, Map<String, V>> { _, property ->
apply { put(property.name, initialValue) }
}
Ivan Pavlov
01/31/2023, 4:50 PMSam
01/31/2023, 4:58 PMPropertyDelegateProvider
is created when the property is declared. So that solution would put the value in the map on instance creation too. I checked by adding some println
calls and it does seem to work that way.Ivan Pavlov
01/31/2023, 5:04 PMRob Elliot
02/03/2023, 9:21 AMSam
02/03/2023, 9:28 AMRob Elliot
02/03/2023, 11:18 AMSam
02/03/2023, 11:23 AMabstract class AbstractPropertyMap<V>(
private val properties: MutableMap<String, V> = mutableMapOf()
) : Map<String, V> by properties {
protected fun mapProperty(initialValue: V) =
PropertyDelegateProvider<Any, Map<String, V>> { _, property ->
properties.apply { put(property.name, initialValue) }
}
}
class Links(
id: String,
otherId: String,
) : AbstractPropertyMap<URI>() {
val self by mapProperty(URI.create("/v1/$id"))
val other by mapProperty(URI.create("/v1/other/$otherId"))
}
Rob Elliot
02/03/2023, 11:38 AM