Fred Friis
12/05/2024, 8:17 PMdata 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
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?Zyle Moore
12/05/2024, 8:22 PMdata class User(
override val email: String,
override val name: String? = "John Smith"
) {
init {
require(!name.isNullOrBlank()) { "name must not be empty" }
}
}
Fred Friis
12/05/2024, 8:25 PMedrd
12/05/2024, 8:30 PMrawName: 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:
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 PMrequire
will throw an exception, which may not be what you wantDaniel Pitts
12/06/2024, 3:07 AMdata 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 }
)
}
Fred Friis
12/06/2024, 4:23 PM