/** * 匹配类型 */ defm7(x: Any): String = x match { case x: String => x case x: Intif x > 5 => x.toString //带if守卫条件的匹配 case _ => "unknow" } println(m7("hello")) //hello println(m7(9)) // 9 println(m7(2)) // unknow ,(虽然2满足Int类型, 但是不满足守卫条件"大于5",所以往下匹配)
defm7_1(v: Any) = v match { casenull => "null" case i: Int => i * 100 case s: String => s case _ => "others" } // 注意:上面case中的i、s都叫模式变量 println(m7_1(null)) // "null" println(m7_1(5)) // 500 println(m7_1("hello")) // "hello" println(m7_1(3.14)) // "others"
// Scala写法 ,每次结束不用写break , _相当于default defm(n:String) = n match { case"a" | "b" => ... case"c" => ... case _ => ... }
3.2 命令行参数解析例子
1 2 3 4 5 6 7 8 9 10 11 12
/** Basic command line parsing. */ objectMain{ var verbose = false// 记录标识,以便能同时对-h和-v做出响应 defmain(args: Array[String]) { for (a <- args) a match { case"-h" | "-help" => println("Usage: scala Main [-help|-verbose]") case"-v" | "-verbose" => verbose = true case x => println("Unknown option: '" + x + "'") // 这里x是临时变量 } if (verbose) println("How are you today?") } }
deffac1(n:Int):Int = n match { case0 => 1 case _ => n * fac1( n - 1 ) } fac1(5) //120
// 同 deffac2: Int => Int = { case0 => 1 case n => n * fac2( n - 1 ) } fac2(5) //120
// 同 使用尾递归 deffac3: (Int,Int) => Int = { case (0,y) => y case (x,y) => fac3(x-1, x*y) } fac3(5,1) // 120
// 同 reduceLeft deffac4(n:Int) = 1 to n reduceLeft( _ * _ )
implicitdeffoo(n:Int) = new { def!= fac4(n) } 5! // 120
// 同 deffac5(n:Int) = (1:BigInt) to n product fac5(5) // 120
3.4 case..if条件匹配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
(1 to 20) foreach { case x if (x % 15 == 0) => printf("%2d:15n\n",x) case x if (x % 3 == 0) => printf("%2d:3n\n",x) case x if (x % 5 == 0) => printf("%2d:5n\n",x) case x => printf("%2d\n",x) } // 或者 (1 to 20) map (x=> (x%3,x%5) match { case (0,0) => printf("%2d:15n\n",x) case (0,_) => printf("%2d:3n\n",x) case (_,0) => printf("%2d:5n\n",x) case (_,_) => printf("%2d\n",x) })
3.5 try..catch..finally
1 2 3 4 5 6 7 8 9
var f = openFile() try { f = newFileReader("inputPath") } catch { case ex: FileNotFoundException => // Handle missing file case ex: IOException => // Handle other I/O error } finally { f.close() }