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);
}
}