scala学习笔记☞三:语法续①

来源:互联网 发布:怎么看mac的系统版本 编辑:程序博客网 时间:2024/05/29 03:15

 ①  parameterize array with types

 

      用例说明一切,一切玄机尽在注视中

      def main(args:Array[String])={
       val greetStr = new Array[String](3);
       val greetStr1:Array[String]=new Array[String](3);
       for(i<- 0 to 2){
         greetStr(i) = "test  "+i
         greetStr1(i) = "test1 "+i
       }
      
       for(i <- (0).to(greetStr.length-1)){
         println(greetStr(i))
       }
       /**
        * when you define a variable with val,the variable can't be reassigned,
        * but the object to which it refers could potentially still be changed.
        */
       greetStr1(1)=" no test1 "
      
       /**
        * if a method takes only one parameter ,you can call it without a dot or parentheses.
        * Note that this syntax only works if you explicitly specify the receiver of the method call.
        */
       for(i <- 0 to greetStr1.length-1){
         println(greetStr1(i))
         Console println greetStr1(i) //println greetStr1(i) is error
       }
     }

 

 Note: scala doesn't technically  have operator overloading.beacause it donesn't actually have operators in traditional sense. Instead, characters such as + , - ,*  and / can be used in method names.

Thus, when you typed 1+2 into the scala interpreter . you ware actually invoking a method named + on the Int object 1 , passing in 2 as parameter.so 1+2  is similar to (1).+(2).

 

Similarly,when an assignment is made to  a variable to which parentheses  and one or  more arguments have been applied, the compiler will transform that into  an invocation of an update method that takes the arguments in parentheses as well as the object to the right of the equals sign.

   eg: greetStr(0)="hello" <==> greetStr.update(0,"hello").

 

So, scala achieves  a conceptual simplicity by treating everything, from arrays to expressions , as objects with methods.


class ParameterizeClass {
  def update(fn:String,sn:String)={
    Console println fn
    Console println sn
  }
  def update1(fn:String,sn:String)={
    Console println "1-->"+fn
    Console println "1-->"+sn
  }
  def delete(fn:String)={
    Console println "delete -->"+fn
  }
  def test(in1:Int):Int={
    var out2 = in1 * 1000
    out2
  }
  def apply(in:Int):Int={
    var out = in * 10
    out
  }
  def apply1(in:Int):Int={
    var out1 = in *100
    out1
  }
  def delete1 ()= Console println "delete1"
 
}
object ParaClassObj{
  def main(args:Array[String])={
    var pc = new ParameterizeClass();
    pc.update("a","b");
    pc.delete1
    pc delete ("delete")
    println(pc(2))//20 I don't understant it that isn't 2000.
    var val_ = pc apply1 3
    println(val_)//300
  }
}