```// 1 fun calculateHour(h: Int, period: String?)...
# codingconventions
e
Copy code
// 1
fun calculateHour(h: Int, period: String?): Int =
  period?.let {
    when(it) {
      "am" -> if (h == HOURS_PER_PERIOD) 0 else h
      "pm" -> (h % HOURS_PER_PERIOD) + HOURS_PER_PERIOD
      else -> h // should not happen
    }
  } ?: h
}
Copy code
// 2
fun calculateHour(h: Int, period: String?): Int =
  if (period == null) {
    h
  } else when (period) {
    "am" -> if (h == HOURS_PER_PERIOD) 0 else h
    "pm" -> (h % HOURS_PER_PERIOD) + HOURS_PER_PERIOD
    else -> h // should not happen
  }
}
s
but what if
Copy code
when (period) {
    null -> h
    <http://Period.AM|Period.AM> -> if (h == HOURS_PER_PERIOD) 0 else h
    <http://Period.PM|Period.PM> -> (h % HOURS_PER_PERIOD) + HOURS_PER_PERIOD
}
👏 5
use the type system to your advantage
e
But of course! For some reason it didn’t occur to me that
null
could be a
when
value. Thank you.
s
to be abundantly clear, my example will only compile if you make
Period
an enum (or sealed class technically but you probably don’t need one to denote AM/PM)
if you just do string matching you’ll need an
else
e
Of course. Only part of my brain was malfunctioning.
😂 2
👍 1
c
The naming is probably suboptimal, it’s not calculating anything, it’s formatting, right?