Parsing xml kotlin android

安稳与你 提交于 2019-12-02 07:23:22

The answer of @daementus is almost perfect. If you want to use constructor injection with default parameters, you have to force Kotlin to generate constructor overloads:

data class Section @JvmOverloads constructor(

    @field:Element(name = "id")
    @param:Element(name = "id")
    val id: Long,

    @field:Attribute(name = "title", required = false)
    @param:Attribute(name = "title", required = false)
    val title: String = ""
)

Without it you will get Constructor not matched for class Section. By default Kotlin generates a constructor with all parameters and a special constructor.

Note: I would prefer to answer in the comments but I don't have enough points.

Indeed, Simple XML Framework has a few problems with Kotlin attributes and it can be a little tricky to get things to work.

To be honest, I am not quite sure what is the problem in your specific case, but I'd guess that the annotation shouldn't be specified for the getter, but rather for the field.

Anyway, I am combining Simple XML and Kotlin data classes this way, and it seems to be working fine :)

data class Section (

    @field:Element(name = "id", required = false)
    @param:Element(name = "id", required = false)
    val id: Long? = null,

    @field:Attribute(name = "title", required = false)
    @param:Attribute(name = "title", required = false)
    val title: String? = null
)

Edit: If you don't want to use data classes (which I highly recommend, but you might have a reason), this should work without the "data" keyword just fine. If you don't wish to create a constructor, just move the attribute declarations directly into the class and get rid of the @param annotation (the @field must stay).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!