var 声明可变的变量
val 不可变常量,一旦初始化,就不能改变
var a:Int 就确切的指明了类型Int,而不采用类型推断
for(a <- 1 until 3;b<- 1 to 3) println(a," ",b)
结果
1 1
1 2
1 3
2 1
2 2
2 3
0.2e-2 0.002
2e2 200
def 定义function
creates a function that returns the max value for two integer values.
def max(x: Int, y: Int): Int = { if (x > y) x else y }
通过递归,求最大公约数
def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
def gcd(x:Long,y:Long): Long {
}
s match {
case "one" => 1
case "two" => 2
case _ => 0
}
function函数也是对象,函数本身也能被当做对象参数 传递 进 function
def filter(inLst:List[Int],cond:(Int)=>Boolean):List[Int]={ if(inLst==Nil) Nil else if(cond(inLst.head)) inLst.head::filter(inLst.tail,cond) else filter(inLst.tail,cond) }
filter(lst,(v:Int)=> v%2==0)