I'm fairly new to Kotlin, and am looking to slim down a data class.
It has two constructors, one for creation based on user input, and one for creation based on database data.
open class Message : Unique {
val timestamp: Long
val contents: String
constructor(contents: String) : super() {
validateMessageContents(contents)
this.contents = contents
this.timestamp = System.currentTimeMillis()
}
constructor(id: String, contents: String, timestamp: Long) : super(id) {
validateMessageContents(contents)
this.contents = contents
this.timestamp = timestamp
}
companion object {
private const val MAX_MESSAGE_LENGTH = 1024
private fun validateMessageContents(contents: String) {
if (contents.isEmpty()) {
throw IllegalArgumentException("Contents cannot be blank/empty")
}
if (contents.length > MAX_MESSAGE_LENGTH) {
throw IllegalArgumentException("Message too long - please limit to $MAX_MESSAGE_LENGTH characters.")
}
}
}
}
The Unique
superclass has a single id: String
property, but will generate a random UUID if the default constructor is called.
I'm wondering - how can I slim down this class? I've fiddled with trying to add a primary constructor, turn it into a data class, but each route I've hit a hurdle.
The things that stick out:
- I'm calling
validateMessageContents()
in both constructors, but can't move it toinit
because thecontents
isn't yet available. - The second constructor, aside from validating the contents, is just two ugly assignment statements.
- The two codepaths to either
super()
orsuper(id)
make it difficult for one of these constructors to be made primary.