gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:55:47 25 4
gpt4 key购买 nike


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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com