Description
Right now, we have two ways to parse something:
LocalDate.parse("2024-01-23")
"2024-01-23".toLocalDate()
With the introduction of datetime formatting (#251), we'll get other ways to do exactly the same:
LocalDate.Formats.ISO.parse("2024-01-23")
LocalDate.parse("2024-01-24", LocalDate.Formats.ISO)
and some others.
The form "2024-01-23".toLocalDate()
looks a bit out-of-place. Parsing a string into a LocalDate
is a way to construct a LocalDate
(and so fits well into the companion object of LocalDate
), not a property of String
. We do have "123".toInt()
, "123".toDouble()
, and other primitive types already. We don't have "1m".toDuration()
for kotlin.time.Duration
.
In terms of separation of responsibilities, String.toLocalDate()
looks strange, but it can be practical when chaining calls. Of the three options below, using toLocalDate
looks the least busy:
getUser(id).await().birthDate.toLocalDate()
LocalDate.parse(getUser(id).await().birthDate)
getUser(id).await().birthDate.let { LocalDate.parse(it) }
The problem is that it's tough to think of cases when such code would be written. Typically, when you accept some unstructured data, it should be parsed and validated first and only then used, so birthDate
should probably already be a LocalDate
and not need any conversion. For String.toInt()
, it's clear when it could be useful: for example, when just a single number is being parsed, which is fairly common. It's more difficult to think of dates that are not part of some larger data structure.