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
Zyle Moore
12/05/2024, 8:22 PM
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
Fred Friis
12/05/2024, 8:25 PM
that's a great idea
but it looks like Kotlin gets mad about var val with this
e
edrd
12/05/2024, 8:30 PM
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()) ...
)
}
}
edrd
12/05/2024, 8:31 PM
Using
require
will throw an exception, which may not be what you want
d
Daniel Pitts
12/06/2024, 3:07 AM
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
Fred Friis
12/06/2024, 4:23 PM
huge thanks all of you! sometimes these seemingly simple things can really trip you up! 😆