samedi 4 août 2018

Kotlin get property in the same order they are declared

I have found some articles on getting properties in Kotlin, but not really something on getting properties in their declared order.

So for now I have created an annotation and used it to declare the order of the properties

@Target(AnnotationTarget.PROPERTY)
annotation class Pos(val value: Int)

data class ClassWithSortedProperties(
    @Pos(1) val b: String,
    @Pos(2) val a: String = "D",
    @Pos(3) val c: String) {

    class PropertyWithPosition(val pos: Int, val value: String)

    fun toEdifact() = this.javaClass.kotlin.declaredMemberProperties
        .map {
            // Get the position value from the annotation
            val pos = (it.annotations.find { it is Pos } as Pos).value
            // Get the property value
            val value = it.get(this)
            PropertyWithPosition(pos, value.toString())
        }
        .sortedBy { it.pos }
        .joinToString(separator = ":") { it.value }
        .trim(':')
}

Is there a better way to get the properties in their declared order?





Aucun commentaire:

Enregistrer un commentaire