incredibly stupid Kotlin question ```data class U...
# random
f
incredibly stupid Kotlin question
Copy code
data class User(
    override val email: String,
    override val name: String? = "John Smith"
)
if someone sends the non-null string "" or " ", name will still be effectively empty but Kotlin doesn't let me
Copy code
data class User(
    override val email: String,
    override val name: String? = if (name.isNullOrBlank()) {"John Smith"} else { name }
)
what's the best way to achieve this?
z
Are you wanting to keep the default value, or prevent blanks, or both? Maybe something like this?
Copy code
data class User(
    override val email: String,
    override val name: String? = "John Smith"
) {
    init {
        require(!name.isNullOrBlank()) { "name must not be empty" }
    }
}
f
that's a great idea but it looks like Kotlin gets mad about var val with this
e
Definitely not a stupid question 🙂 For non-data classes, you could pass a parameter like
rawName: String
in the constructor and declare a
val name: String = if (rawName.isNullOrBlank()) ...
. For data classes, you can use the "companion invoke fun" trick and make the data class constructor private:
Copy code
data class User private constructor(...) {
  companion object {
    operator fun invoke(email: String, name: String) = User(
      email = email,
      name = if (name.isNullOrBlank()) ...
    )
  }
}
Using
require
will throw an exception, which may not be what you want
d
Copy code
data class User(
     val email: String,
     val name: String
) {
    constructor(
        email: String,
        name: String? = null,
    ) : this(
        email = email,
        name =  if (name.isNullOrBlank()) {"John Smith"} else { name }
    )
}
f
huge thanks all of you! sometimes these seemingly simple things can really trip you up! 😆
kodee pleased 1