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

 ①  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
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值