Scala會根據你定義屬性時候使用的關鍵字:var,val,private來選擇是否自動生成getter和setter方法。而且不容許你重寫Scala的setter和getter方法。若是你要重寫這兩個方法你會看到以下編譯錯誤:java
scala> :paste // Entering paste mode (ctrl-D to finish) class Person(private var name: String) { def name = name def name_=(aName: String) {name = aName} } // Exiting paste mode, now interpreting. <console>:12: error: overloaded method name needs result type def name = name ^ <console>:13: error: method name_= is defined twice conflicting symbols both originated in file '<console>' def name_=(aName: String) {name = aName} ^
Scala默認對於Person類的name屬性,自動生成的getter和setter方法名分別是name和name_=。可是你能夠變通的用另外一種方式來避開Scala的setter和getter方法名規範,好比咱們把name屬性名改成_name那麼這個時候Scala默認生成的getter和setter方法是_name和_name_=,你只要不用這兩個方法名就能夠了。ide
scala> :paste // Entering paste mode (ctrl-D to finish) class Person(private var _name: String) { def name = _name def name_=(aName: String) {_name = aName} override def toString = s"name is $name" } // Exiting paste mode, now interpreting. defined class Person scala> val p = new Person("Li Ming") p: Person = name is Li Ming
由於name屬性是private var修飾的,因此它是可變,再加上咱們定義了本身的getter方法。咱們能夠改變並獲取name屬性值。this
scala> val p = new Person("Li Ming") p: Person = name is Li Ming scala> p.name = "Wang Wei" p.name: String = Wang Wei scala> p.name res2: String = Wang Wei
咱們來看一下反編譯後的class文件中的getter和setter方法,你會看到一個getter方法:symbol();一個setter方法symbol_$eq。這就是Scala生成getter和setter的規範。scala
class Stock (var symbol: String) public class Stock extends java.lang.Object{ public java.lang.String symbol(); public void symbol_$eq(java.lang.String); public Stock(java.lang.String); }
總結一下:重定義Scala默認生成的getter和setter方法,咱們須要注意下面幾點。code
必定記住要使用private關鍵字來修飾構造方法參數,不然Scala會生成一對默認的getter和setter方法。get
scala> :paste // Entering paste mode (ctrl-D to finish) class Stock (var _symbol: String) { def symbol = _symbol def symbol_=(s: String) { this._symbol = s println(s"symbol was updated, new value is $symbol") } } // Exiting paste mode, now interpreting. defined class Stock
反編譯生成的class文件,你會發現除了你本身定義的getter和setter方法外,Scala還爲你生成了一對默認的getter和setter方法。it
public class Stock extends java.lang.Object{ //Scala自動生成的getter和setter方法 public java.lang.String _symbol(); public void _symbol_$eq(java.lang.String); //自定義的getter和setter方法 public java.lang.String symbol(); public void symbol_$eq(java.lang.String); public Stock(java.lang.String); }
使用private關鍵修飾後,反編譯生成的class文件。console
public class Stock extends java.lang.Object{ public java.lang.String symbol(); public void symbol_$eq(java.lang.String); public Stock(java.lang.String); }