kotlin: Value object with input validation

November 9, 2019

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 {
          @JvmStatic
          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:

  • java.time.MonthDay Immutable. Validates the day/month combination. Sample usage: MonthDay.of(11, 7)
  • java.time.Instant Immutable. Good fit with epoch seconds.
    1. Instant.ofEpochSecond(1573391885) Convert epoch seconds to an Instant.
    2. Instant.now() Current time.
    3. asOf.atZone(tz.toZoneId()).toLocalDate() Get a local date from the Instant asOf.
  • java.time.ZonedDateTime Immutable. Go from month, day, etc to an Instant, for example:
    
        ZonedDateTime.of(
            2019,
            11,
            7,
            8,
            21,
            0,
            0,
            TimeZone.getTimeZone(" US/Eastern") 
        ).toInstant()
        

Tags: kotlin