簡體   English   中英

在Scala的構造函數上重新分配var參數

[英]Reassigning a var parameter on Scala's 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM