title: Avoid Repeated Calls to the Same Function in Scala in If Else
body: <p>I have the following code snippet that I would like to optimize:</p>
  <pre><code>import org.joda.time.{DateTime, Days, Months, Weeks, Years}
  
    @scala.annotation.tailrec
    def optimize(start: DateTime, end: DateTime, acc: List[(DateTime, DateTime)]): List[(DateTime, DateTime)] = {
  
      def doDaysExist(startDate: DateTime, endDate: DateTime): Boolean = {
        Days.daysBetween(startDate, endDate).getDays != 0
      }
  
      if (Years.yearsBetween(start, end.plusDays(1)).getYears != 0) {
        val years = Years.yearsBetween(start, end.plusDays(1)).getYears
        val newStart = start.plusYears(years).minusDays(1)
        if (doDaysExist(newStart, end)) {
          optimize(newStart, end, (start, newStart) +: acc)
        } else (start, end) +: acc
      } else if (Months.monthsBetween(start, end.plusDays(1)).getMonths != 0) {
        val months = Months.monthsBetween(start, end.plusDays(1)).getMonths
        val newStart = start.plusMonths(months).minusDays(1)
        if (doDaysExist(newStart, end)) {
          optimize(newStart, end, (start, newStart) +: acc)
        } else (start, end) +: acc
      } else if (Weeks.weeksBetween(start, end.plusDays(1)).getWeeks != 0) {
        val weeks = Weeks.weeksBetween(start, end.plusDays(1)).getWeeks
        val newStart = start.plusWeeks(weeks).minusDays(1)
        if (doDaysExist(newStart, end)) {
          optimize(newStart, end, (start, newStart) +: acc)
        } else (start, end) +: acc
      } else {
        // For sure days
        (start, end) +: acc
      }
    }
  </code></pre>
  <p>As it can be seen that the if condition and the next statement that follows are kind of duplicate code. Is there a better way to make it better and cryptic? I have to step through this hierarchy as I have to first check the year, then the month, then the week and then the day.</p>
  <p>I can think of extracting the repeated code block into lambdas, but is that good enough? I can't think of rewriting it as a Map as that code block runs in a tail recursive function.</p>