https://kotlinlang.org logo
#codereview
Title
# codereview
k

KV

03/02/2022, 2:11 PM
Hello peps, I have a state class like below:
Copy code
data class ViewState(
    var startDateTime: LocalDateTime? = null,
    var endDateTime: LocalDateTime? = null,
    var totalBreakDuration: Duration? = null,
    var onEditClick: () -> Unit = {}
) {
    fun totalDuration() = startDateTime?.let { startDateTime ->
        endDateTime?.let { endDateTime ->
            Duration.between(startDateTime, endDateTime)
        }
    }

    fun workDuration() = totalDuration()?.minus(totalBreakDuration!!)
}
I have stateImplementation like Below:
Copy code
state.startDateTime?.let {
                    ViewItemState(
                        label = "label",
                        value = it.format(ISO_LOCAL_DATE)
                    )
                }?.let(binding.dateItem::setupWithState)
-----------------------------------------------------------------
                state.startDateTime?.let {
                    ViewItemState(
                        label = "label"
                        value = it.format(ISO_LOCAL_TIME)
                    )
                }?.let(binding.startTimeItem::setupWithState)
-----------------------------------------------------------------------------
                state.endDateTime?.let {
                    ViewItemState(
                        label = "label",
                        value = it.format(ISO_LOCAL_TIME)
                    )
                }?.let(binding.endTimeItem::setupWithState)
-----------------------------------------------------------------------------
                state.totalDuration()?.let { DurationFormat().format(it) }?.let {
                    ViewItemState(
                        label = "label",
                        value = it
                    )
                }?.let(binding.totalTimeItem::setupWithState)
-----------------------------------------------------------------------------
                state.totalBreakDuration?.let { DurationFormat().format(it) }?.let {
                    ViewItemState(
                        label = "label,
                        value = it
                    )
                }?.let(binding.totalBreakTimeItem::setupWithState)
-----------------------------------------------------------------------------
                state.workDuration()?.let { DurationFormat().format(it) }?.let {
                    ViewItemState(
                        label = "label",
                        value = it
                    )
                }?.let(binding.workTimeItem::setupWithState)
My questions are: 1. How to refactor the code? 2. How to remove so many times .let {} for each and every methods?
3 Views