scalaforward-reference

Solving wrong forward reference error in scala


How to solve wrong forward reference error in scala. What exactly is that error means?

def daysInMonth(year: Int, month: Int): Int = {
      val daysInMonth: Int = month match {
        case 1 => 31
        case 3 => 31
        case 5 => 31
        case 7 => 31
        case 8 => 31
        case 10 => 31
        case 12 => 31
        case 2 => {
          if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) 29 else 28
        }
        case _ => 30
      }

      daysInMonth
    }

The below statement shows the forward reference error

println(daysInMonth(2011,12))

Solution

  • The error was caused by the fact that you were trying to return a variable with the same name of your function.

    The solution is much simpler than you think:

    object WrongForwardReference {
    
      def main(args: Array[String]): Unit = {
        println(daysInMonth(2011,12))
      }
    
      def daysInMonth(year: Int, month: Int): Int = month match {
          case 1 => 31
          case 3 => 31
          case 5 => 31
          case 7 => 31
          case 8 => 31
          case 10 => 31
          case 12 => 31
          case 2 => {
            if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) 29 else 28
          }
          case _ => 30
      }
    
    }
    

    A simplified version is this one:

      def daysInMonth(year: Int, month: Int): Int = month match {
          case 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31
          case 2 => {
            if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) 29 else 28
          }
          case _ => 30
      }