object A
{  
    def main(args:Array[String]):Unit=
  {
        val b = new B();
        b(0)="scala"; 
        print(b(0)); // scala 索引器的实现
    }
}

class B
{
    private val content:Array[String] = Array("hello","world");//Array[String]("hello","world"); 或者 Array.apply[String]("hello","world"); Array.apply("hello","world");
    def apply(index:Int):String =
    {
        return this.content(index);//return this.content.apply(index);
    }

    def update(index:Int,item:String):Unit =
    {
        this.content(index)=item;//this.content.update(index,item);
    }
}
 

class R(n:Int,d:Int )
{
private val g = gcd(n,d);
val number = n/g;
val denom = d/g;

def this(n:Int)=this(n,1);

private def gcd(a:Int,b:Int):Int = if(b==0) a else gcd(b,a%b);//recursive method gcd needs result type
override def toString() = if(this.denom==1) this.number.toString() else this.number+"/"+this.denom;

def +(that:R)= new R(this.number*that.denom+that.number*this.denom*that.number,this.denom*that.denom);
def *(that:R)= new R(this.number*that.number,this.denom*that.denom);
def /(that:R)= new R(this.number*that.denom,this.denom*that.number);
}

object R
{
def apply(n:Int,d:Int)= new R(n,d);
def apply(n:Int)=new R(n);
}


object A
{  
def main(args:Array[String]):Unit=
{
print(R(2,3)/R(1,3));
}
} 

  

 

 

 

posted on 2012-08-21 23:22  scala  阅读(333)  评论(0编辑  收藏  举报