Can Kotlin data class have more than one constructor?

前端 未结 9 1334
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 18:48

I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

data class User(val name: String, val age:         


        
9条回答
  •  情歌与酒
    2020-12-30 19:21

    Default values in the primary constructor eliminates many needs for secondary constructors, but if the needed instance depends on logic based on data that must be analyzed the better answer may be to use a companion object.

    data class KeyTag(val a: String, val b: Int, val c: Double) {
        companion object Factory {
            val empty = KeyTag("", 0, 0.0)
    
            fun create(bigString: String): KeyTag {
                // Logic to extract appropriate values for arguments a, b, c
                return KeyTag(a, b, c)
            }
    
            fun bake(i: Int): KeyTag = KeyTag("$i", i, i.toDouble())
        }
    }
    

    Usage is then:

    val ks = KeyTag.create("abc:1:10.0")
    val ke = KeyTag.empty
    val kb = KeyTag.bake(2)
    

提交回复
热议问题