在Scala的构造函数上重新分配var参数

nob*_*ody 2 parameters constructor scala


object ReassignTest extends App {
  class X(var i : Int)

  def x = new X(10)
  x.i = 20  // this line compiles

  println(x.i)  // this prints out 10 instead of 20, why?
}
Run Code Online (Sandbox Code Playgroud)

那么我将如何为参数创建一个setter i

drs*_*ens 13

您定义x为一种方法,X每当您"调用"它时返回一个新方法.

def x = new X(10) //define a function 'x' which returns a new 'X'
x.i = 20  //create a new X and set i to 20

println(x.i) //create a new X and print the value of i (10)
Run Code Online (Sandbox Code Playgroud)

定义x为一个值,而行为将如您所愿

val x = new X(10) //define a value 'x' which is equal to a new 'X'
x.i = 20  //set 'i' to be to 20 on the value 'x' defined above 

println(x.i) //print the current value of the variable i defined on the value 'x'
Run Code Online (Sandbox Code Playgroud)

  • Antoras虽然在技术上是正确的,但不要过分强调方法和功能之间的区别.感谢Scala的统一方法,差异模糊了. (4认同)