https://kotlinlang.org logo
#klaxon
Title
a

Andrew Giorgio

02/17/2020, 8:23 PM
I define these classes:
Copy code
@TypeFor(field = "type", adapter = ShapeTypeAdapter::class)
open class Shape(val type: String)

data class Rectangle(val width: Int, val height: Int) : Shape("rectangle")
data class Circle(val 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")
    }
}
and then I call the following (in a test), which gives me the error.
Copy code
val result = Klaxon().parseArray<Shape>(
        """
            [
                { "type": "rectangle", "width": 100, "height": 50 },
                { "type": "circle", "radius": 20}
            ]
         """
)