您的位置:首页 > 其它

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

2009-02-17 14:29 441 查看
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+" ")
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: