when doing functional programming in kotlin, how d...
# android
u
when doing functional programming in kotlin, how do you structure your code? For example:
data 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 ?
c
There is another option you can use to format code right to the side of the one you chose called “code block”
Copy code
data 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 this
💯 1
m
Normally, I prefer to use extension functions (Defining an empty companion object makes it possible to do this without an instance... see below). The exception being when there's a private constructor, in which case I might define a few "core" methods on the companion object directly, and then do the rest as extensions. Also, to me,
toDay()
feels like something you'd call on an instance, not a companion object.
Copy code
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.
Copy code
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 = /* ... */
1