scala - 在 Scala 的构造函数上重新分配一个 var 参数

标签 scala parameters constructor


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

那么我如何为参数 i

创建一个 setter

最佳答案

您将 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)

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'

关于scala - 在 Scala 的构造函数上重新分配一个 var 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9980759/

相关文章:

scala - SBT 无法通过 HTTPS 解决 AWS EC2 实例对第三方存储库的依赖关系

scala - 了解 Scala GADT 支持的限制

javascript - 普通函数和箭头函数在 _proto_ 构造函数方面有何不同?

c# - 如果方法参数也是 "out"参数,如何使用反射检查方法参数是否为 Nullable<>?

c++ - 从构造函数中捕获异常意味着我的实例之后超出了范围

java - 按钮在扩展 JButton 时不执行任何操作,但它通过返回 JButton 的方法来执行此操作

scala - 从 Spark scala 中的数据帧创建 map

scala - 从 Scala 编译器插件生成 Scala 代码树

java - 将一个对象添加到将另一个对象作为参数的 ArrayList

python-2.7 - Selenium Webdriver 与 Python - driver.title 参数