0xf1f1
04/08/2024, 8:54 PMdata class TravelDate(val date: Instant)
fun create(date: Instant)
fun toDay(date: TravelDate): Day
fun toTime(date: TravelDate): LocalTime
What is the best what to group these related classes ?
One approach would be a companion object:
data class TravelDate(val date: Instant) {
companion object {
fun create(date: Instant): TravelDate
fun toDay(date: TravelDate): Day
fun toTime(date: TravelDate): LocalTime
}
}
But this tightly couples the functions to the data class, such they cannot be accessed independent of it. An alternative is to wrap everything in an object:
object TravelDate {
TravelDate(val date: Instant)
fun create(date: Instant)
fun toDay(date: TravelDate): Day
fun toTime(date: TravelDate): LocalTime
}
Which is more preferable ?Cicero
04/09/2024, 12:53 PMdata class TravelDate(val date: Instant) {
companion object {
fun create(date: Instant): TravelDate
fun toDay(date: TravelDate): Day
fun toTime(date: TravelDate): LocalTime
}
}
Will make your code look like thisMatthew Feinberg
04/10/2024, 1:14 AMtoDay()
feels like something you'd call on an instance, not a companion object.
data class TravelDate(val date: Instant) {
companion object
}
fun TravelDate.Companion.fromMonthDateYear( month: Int, day: Int, year: Int ) = TravelDate( Instant.parseIsoString(/* ... */) )
fun TravelDate.toDay() : Day = /* ... */
vs.
data class TravelDate private constructor (val date: Instant) {
companion object {
fun fromInstant( date: Instant ) = TravelDate(date)
}
}
fun TravelDate.Companion.fromMonthDateYear( month: Int, day: Int, year: Int ) = TravelDate.fromInstant( Instant.parseIsoString(/* ... */) )
fun TravelDate.toDay() : Day = /* ... */