Andrew Giorgio
02/21/2020, 12:06 AMimport com.beust.klaxon.TypeAdapter
import com.beust.klaxon.TypeFor
import kotlin.reflect.KClass
@TypeFor(field = "type", adapter = ShapeTypeAdapter::class)
open class Shape(val type: String) {
val width: Int = -1
val height: Int = -1
val radius: Int = -1
}
class Rectangle(width: Int, height: Int) : Shape("rectangle")
class Circle(radius: Int) : Shape("circle")
class ShapeTypeAdapter : TypeAdapter<Shape> {
override fun classFor(type: Any): KClass<out Shape> = when (type as String) {
"rectangle" -> Rectangle::class
"circle" -> Circle::class
else -> throw IllegalArgumentException("Unknown type: $type")
}
}
This allows the parse to happen without errors. However, the results are unexpected. I wrote the following test, and put the results of the print statements in comments on the same line:
val result = Klaxon().parseArray<Shape>(
"""
[
{ "type": "rectangle", "width": 25, "height": 75},
{ "type": "circle", "radius": 20}
]
"""
)
println(result?.get(0)?.width) //Prints 25
println(result?.get(0)?.height)//Prints 75
However, based on my understanding of how this code should work, the actual width and height parameters that were read from the JSON string should be unused, and the print statements should both output -1. Especially as the width and height properties on Shape are neither mutable nor open.