kotlin: Value object with input validation

November 9, 2019

Note: Subsequent to writing this post, I found a better approach.

The software used for this howto is Kotlin 1.3.50.

data class Hour(val n: Int) {
  init {
      require(n in 0..23) { "invalid hour $n" }

  companion object {
      fun parse(x : String) = Hour(x.toInt())


Hat tip to Alexis King's blog post Parse, don’t validate.

Note that in Kotlin, the Int type means a compiler error if your code tries to instantiate this class with a null value. (The type Int? would tell the compiler a null is OK.)

Other useful Java value objects having to do with time: