scala getter and setter
2014-04-26 16:29
302 查看
package exp { object Main { def main(args: Array[String]): Unit = { B.name ="Fred"; println(B.getName()) } } class A { private var n: String = null; val getName = () => this.n; // println(a.getName); 返回<function0> 对象或类用val 定义的方法不能省略括号否则返回函数本身 val setName = (x: String) => this.n = x; //对象或类用val定义的方法如果有参数,省略点号和参数的括号是可以的 val updateName: String => Unit = x => this.n = x; //getter setter 属性定义必须这么做,方法定义可以用上面的def val 等各种方法 def name = this.n; def name_=(x: String) = this.n = x; //或 def name_= : String=>Unit = x => this.n = x; } //object 相当于java中的静态方法,其实是用class 的单例静态对象实现的,所以可以继承java的类,但是object不能被继承了 object B extends A; //object C extends B -> not found:Type B }
抽象 val 只生成抽象getter,抽象var生成抽象的getter和setter
trait AbstractTime { val hour:Int; var minute:Int; }
生成的java代码如下
public interface AbstractTime { public abstract int hour(); public abstract int minute(); public abstract void minute_$eq(int i); }
trait TRat { val n:Int; val d:Int; val n_d = n/d; //lazy val n_d = n/d; } object Main { def main(args: Array[String]): Unit = { val x = new {val n=20; val d=5} with TRat; //new TRat{val n=20; val d=5}; //如果这么构造的话,两个值的匿名类结构体对象在构造TRat匿名类后构造, //因此n/d将出现div zero异常,除非 val n_d 设置为lazy val 或 def println(x.n_d); } }
相关文章推荐
- ES6 getter and setter
- JavaScript Getter And Setter
- (一)scala方法/包/getter/setter
- getter and setter In java
- [Objective-C] class add a property and its setter and getter
- defineGetter and defineSetter in Firefox
- About Setter and Getter
- Getter And Setter取消前缀
- __defineGetter__ and __defineSetter__
- Javascript Getter/Setter and prototype(extend dom)
- 在反射中如何调用类中的Setter()AndGetter()方法
- @synthesize 何时用?:当同时实现setter and getter
- Getter and setter
- Why getter and setter methods are evil
- Scala学习之类和属性篇(五):getter和setter方法
- OO设计精要:封装,还是封装(有感于“Why getter and setter methods are evil ”by Allen Holub )
- iOS 中 setter and getter
- Eclipse中generate getter and setter对boolean的反应
- as3——跳出方法,getter and setter,子类实施超类的译本
- scala属性的getter和setter方法