Scala - 基本语法

block of code as a param

— ex:
if we have a function like

def example(name:string){
var char = name[0]
char+'good'
}={


}

the function example want to receive two params

  • name
  • the result of certain block of code (we need use {} for the code block)

if - else

var x = 30;

if( x == 10 ){
println("X 的值为 10");
}else if( x == 20 ){
println("X 的值为 20");
}else if( x == 30 ){
println("X 的值为 30");
}else{
println("无法判断 X 的值");
}

这个语法很普通 js一样一样的

Pattern matching

def matchTest(x: Any): Any = x match {
case 1 => "one"
case "two" => 2
case y:Int if y >4 => "more than four"
case y: Int => "scala.Int"
case _ => "many"
}

println(matchTest("two"))
println(matchTest("test"))
println(matchTest(1))
println(matchTest(6))

模式匹配首先很想switch.
逐个匹配然后返回值.
匹配比switch 更灵活

  1. y:Int 可以加类型
  2. y 算是把匹配项付给临时的变量
  3. 可以给匹配项再加条件筛选 y:Int if y >4
  4. _ 相当于匹配任何值,类似switch 的default