We have an abstract Java class (which we can't modify) called AbstractClass
that we want to implement in Kotlin. A requirement is the Kotlin implementation is serializable/deserializable to JSON using vanilla Jackson Databind. This has lead us to the following implementation:
class MyClass(private val data: MyClassData? = null) : AbstractClass<MyClassData>(MyClass::class.java, "1") {
data class MyClassData(var name: String = "", var age: Int = 0) : AbstractData
override fun getData(): MyClassData? {
return data
}
}
This class will always be used from Java and currently you can instantiate it like this (Java):
MyClass myClass = new MyClass(new MyClassData("John Doe", 25));
But we'd prefer to instantiate it like this instead:
MyClass myClass = new MyClass("John Doe", 25);
I can of course change the Kotlin code to something like this:
class MyClass(@JsonIgnore private var name: String = "", @JsonIgnore private var age: Int = 0) : AbstractClass<MyClassData>(MyClass::class.java, "1") {
data class MyClassData(var name: String = "", var age: Int = 0) : AbstractData
private var data : MyClassData? = null
init {
data = MyClassData(name, age)
}
override fun getData(): MyClassData? {
return data
}
}
but this is very verbose and kind of defeats the purpose of using Kotlin.
What I think I'd like to do is something like this (pseudo code):
class MyClass(private val data: MyClassData? = null by MyClassData) : AbstractClass<MyClassData>(MyClass::class.java, "1") {
data class MyClassData(var name: String = "", var age: Int = 0) : AbstractData
override fun getData(): MyClassData? {
return data
}
}
(note the by MyClassData
in the MyClass
constructor which obviously doesn't work)
I.e. I'd like to somehow destruct or delegate the constructor of MyClass to take the same arguments as MyClassData without duplicating them. Is this something you can do in Kotlin or is there another way to solve it without adding too much code?