I have a data class, used in many different places:
data class Person(
val name: String,
val lastName: String
)
And I want to make sure name
and lastName
never contains blank white spaces (like using replace(" ", "")
), how can I use this for the data class?
Ideally something like this (even though I know this is not possible):
data class Person(
val name: String.replace(" ", ""),
val lastName: String.replace(" ", "")
)
2
Answers
One approach could be:
But this is a bit more complicated problem actually, why? because you probably want 2 data classes having same names but with different pattern of white spaces to be considered equal right? and data class would fail in that regard as it will match exact parameter values, so its better to get rid of data class keyword and just use a plain old class with overriden
equals()
andhashcode()
method as per your use case. You can override these methods in your data class as well, but then there won’t be much point in using a "data" classI had a similar use case, we were trying to have a third field which was a projection of two other fields. We have used the following approach:
So similarly, if you don’t mind mutability of that column (probably you do in this case), you can use this approach.
init
block will override the parameter coming from the default constructor.One alternative thing you might want to do is validate the call. Inside the data class, add this init block,
Or you can even do more complex checks such as
Note: This approach might not work as expected, because the field defined inside the class is going to be excluded from
equals
andtoString()
methods. You might want to just write a plainclass
.