解决scala中错误的前向引用错误

Solving wrong forward reference error in scala

如何解决scala中错误的前向引用错误。该错误的确切含义是什么?

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
    }

下面的语句显示前向引用错误

println(daysInMonth(2011,12))

错误是由于您试图 return 一个与您的函数同名的变量。

解决方法比你想象的要简单得多:

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
  }

}

简化版是这个:

  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
  }