Scala - 方法变量不是不可变的

Scala - method variables not immutable

似乎是 Scala 中的一个错误,它可以让您改变方法变量名。

在此示例中,编译器决不允许在同一方法块中再次声明参数 name

object App {

  def main(args: Array[String]): Unit = {
    testMethod()
  }

  def testMethod(name: String = "John Smith"): Unit = {
    val name = "John Doe"
    println(name)
  }

}

是否有任何关于改变方法变量名称的解释?

输出

John Doe

这不是错误,而是一个功能。这叫做shadowing.

如果你能做到这一点,真正可能是一个错误:

def testMethod(name: String = "John Smith"): Unit = {
  name = "John Doe" // does not compile
  println(name)
}

注意 name 不是 val 并试图 re-assign 传入参数的新值