在Scala';s构造函数

在Scala';s构造函数,scala,parameters,constructor,Scala,Parameters,Constructor,那么,我如何为参数I创建一个setter呢?您将x定义为每次“调用”它时都返回一个新的x的方法 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? } 将x定义为一个值,行为将如您所期望的那样 def x

那么,我如何为参数
I
创建一个setter呢?您将
x
定义为每次“调用”它时都返回一个新的
x
的方法


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?
}
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)

def
不声明函数,它声明了一个可能返回函数的方法。虽然Antoras在技术上是正确的,但不会过分强调方法和函数之间的区别。多亏了Scala的统一方法,两者之间的区别变得模糊了。@Antoras在技术上(如规范所述),
def
声明了一个函数,该函数可能返回一个匿名函数。但我完全同意你评论的精神。
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'