Kotlin - generate toString() for a non-data class

后端 未结 6 953
终归单人心
终归单人心 2020-12-17 08:17

Situation:

I have a class with lateinit fields, so they are not present in the constructor:

class ConfirmRequest() {
           


        
6条回答
  •  遥遥无期
    2020-12-17 08:32

    What about using Kotlin reflection? I am into Kotlin for a few days, so apologies, if I misunderstood question, or wrote "Kotlin inefficient" example.

    override fun toString() : String{
        var ret : String = ""
        for (memberProperty in this.javaClass.kotlin.memberProperties){
            ret += ("Property:${memberProperty.name} value:${memberProperty.get(this).toString()}\n");
        }
        return ret
    }
    

    This can also could be implemented in newly created interface for example ToString2Interface as fun toString2. Then all classes which implements ToString2Interface would have toString2()

提交回复
热议问题