How can i trim String properties which is on data ...
# getting-started
u
How can i trim String properties which is on data class constructor? the data class is below.
Copy code
data class Member(
    val firstName: String,
    val lastName: String,
    val phone: String,
)
What i want to do is force Member instance to created with triming it’s String properties. So there are not Member instances that has blank values at String type properties(lastName, firstName)! The easiest way is binding trimed value at Member’s primary constructor, but it is still possibile create instance that have with blank value at their String type properties. Can i ask you the appropriate way?
l
If you specify a property in the primary constructor, then you cannot specify how the input parameter at that position is assigned to the property. Since data class requires primary constructor to have no bare parameter, you may not want to use data class, or have a factory function that validates the input then creates a corrected instance.
👀 1
Copy code
class Data(int: Int) {
    val int: Int = int.coerceAtLeast(0)
}

data class Data(val int: Int) {
    companion object {
        fun coerced(int: Int): Data {
            return Data(int.coerceAtLeast(0))
        }
    }
}
Note that privatizing the primary constructor of a data class will send you a warning saying that the generated
copy
function can access the primary constructor and this will bypass your validation process in places other than
init {}
block. The choice is yours, but be aware of these potential bugs.
🙌 1
u
@Loney Chou thank you for your answer! you helped me what to choice. The factory function is the better way i think, rather than appear ide alert message privatizing the primary constructor of a data class. thank you