skip to Main Content

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


  1. One approach could be:

    data class Person(
        private val name: String,
        private val lastName: String
    ) {
        fun getName() = name.replace(" ", "")
        fun getLastName() = lastName.replace(" ", "")
    }
    

    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() and hashcode() 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" class

    Login or Signup to reply.
  2. I 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:

    data class Person(
      val name: String,
      val lastName: String,
      var id: String = "",
    ) {
      init {
        id = "$name#$lastName"
      }
    }
    
    

    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,

    data class Person(
      val name: String,
      val lastName: String,
    ) {
      init {
        check(name.contains(" ").not()) { "Name should not contain empty spaces." }
        check(lastName.contains(" ").not()) { "Last name should not contain empty spaces." }
      }
    }
    

    Or you can even do more complex checks such as

    check("[a-zA-Z]+".toRegex() matches name) { "Name should only contain alphanumeric characters!" }
    

    Note: This approach might not work as expected, because the field defined inside the class is going to be excluded from equals and toString() methods. You might want to just write a plain class.

    data class Person(
      val name: String,
      val lastName: String,
    ) {
      val id: String
      init {
        id = "$name#$lastName"
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search