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

被折叠的 条评论
为什么被折叠?



