Reputation: 130
I was wondering if there is a clever way to automatically generate setters/getters of a child class within the parent class with metaprogramming, like that :
open class TableClass {
protected val t: MutableMap<String,Any> = mutableMapOf()
fun attribute (k:String,v:Any) {
t[k] = v
}
}
class Coordinates () : TableClass() {
//Automatically generate that through metaprogramming in the parent class
var x : Int
get() = t["x"] as Int
set(v) { this.attribute ( "x", v ) }
var y : Int // ...
}
Thank you for your attention !
Upvotes: 1
Views: 130
Reputation: 28302
Contrary to Python, which I believe you reference here, Kotlin is a strongly typed language, so it is not possible to generate properties or fields dynamically.
You can use delegated properties to at least make it a little more "dynamic":
class Coordinates () : TableClass() {
var x : Int by t
var y : Int by t
}
The reason why it works is because your are lucky ;-) Kotlin automatically provides a way to delegate properties to Map<String,Any>
. But you still have to declare all required properties and delegate them. You can also implement your own property delegators, other than maps.
Other than that, you can use annotation processing to automatically generate the Kotlin source code while compiling, but this is much longer story and this is probably not what you really want.
Upvotes: 3