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+" ")
}
}