scala学习笔记☞二:简单语法练习

本文详细介绍了Scala语言的基础概念,包括不可变变量val与可变变量var的区别、定义函数的方法、数组操作方式、条件判断与循环结构的使用,以及如何进行迭代操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1. var 和 val的区别

     A val is similar to a final variable in Java. so, once initialized ,that  can never be reasigned.

 

     A var is similar to a no-final variable in Java.

 

 2. define some functions;

 

     def max(x:Int,y:Int):Int={

          if(x>y)

             x

          else

            y

    }

 

    def: starts a function definition

 

    max: function name

 

   x:Int,y:Int  : parameter list in parentheses

 

   :Int   :  function's result type

 

Note: 1) scala's if expression  can result in  a value, So, It's similar to  java's ternary operator(x?y:z).

           2) sometimes the scala compiler will require you to specify the result type of a function. If the function don't has a result,but  you to specify unit tha is the result type . But, If the function is recursive ,for example , you must explicitly specify the function's result type.

 

 3. Array of the scala

 

    In scala,arrays are zero based,as in java, buy you access an element by specifying an index in parentheses rather than square brackets.

    eg: the first element  in a scala  array named steps in steps(0),not steps[0].

 

 

 4. comment of the scala

   

     as with Java.

 

 5. Loop with  While  and decide  with if

 

     1>  Java's i++ and ++i don't work in scala! To increment  in scala ,you need to say either i=i+1 or i += 1;

     2> You write while loops in scala in much the same  way  as in java.

 6. Iterate with foreatch and for

     eg:

   def main(args:Array[String])={
    
      var arg = Array("hello","scala","great");
      println(" 1:")
      arg.foreach((arg:String)=>print(arg+"   "))
      println
      println(" 2:")
      //要注明类型时需要括号,否则括号可省略。
      arg.foreach(arg=>print(arg+" "))
      println
      println(" 3:")
      //if a function literal consists of one statement that takes a single statement,
      //you need not explicitly name and specify the argument.
      arg.foreach(println)
      println("-----");
      for(argItem <- arg){//Note: argItem is a val.(not var)
        print(argItem+" ")
      }
   }

 

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值