Can Kotlin data class have more than one constructor?

前端 未结 9 1316
没有蜡笔的小新
没有蜡笔的小新 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:14

    I wanted to have a class similar to below (with a constructor that parses an input)

    data class Data(val a: String, val b: String) {
        constructor(spaceSeparated: String) { // error because we don't call this()
            val split = spaceSeparated.split(" ")
            this(split.first(), split.last()) // error again because it's not valid there
        }
    }
    

    The solution is to do this:

    data class Data(val a: String, val b: String) {
        companion object {
            operator fun invoke(spaceSeparated: String): Data {
                val split = spaceSeparated.split(" ")
                return Data(split.first(), split.last())
            }
        }
    }
    

    And it can be called just as if it were a constructor

提交回复
热议问题