Programming in Scala 2nd 读书笔记 2
Build-in Control Structure
for的声明里跟上if可以直接过滤符合条件的元素到for循环体里调用
多级的for循环可以直接在for里面声明
多级循环
{}内的语句会自动推断分号的位置
()里必须写清楚分号
for的声明后跟上yield会将for声明里符合条件的元素重新返回成为一个Array
不过函数式风格的编程里是没有for循环的,一般是用递归实现
多使用自带的foreach之类的接口
match 类似java的switch
但是不需要在每个case后面跟break;
默认的case 使用_
函数式编程里不要使用break和continue
虽然scala提供了机制可以使用
不过最好忘了他
Functions and Closures
可以在方法体内定义新的方法提高代码可读性和代码重用,避免满屏的私有方法
函数对象的声明
val func=(x: Int) => x + 1
def sum(a: Int, b: Int, c: Int) = a + b + cval b = sum(1, _: Int, 3)b(2)
object FileMatcher { private def filesHere = (new java.io.File(".")).listFiles private def filesMatching(matcher: String => Boolean) = for ( file <filesHere; if matcher(file.getName) ) yield file def filesEnding(query: String) = filesMatching(_.endsWith(query)) def filesContaining(query: String) = filesMatching(_.contains(query)) def filesRegex(query: String) = filesMatching(_.matches(query))}def withPrintWriter(file: File)(op: PrintWriter => Unit) { val writer = new PrintWriter(file) try { op(writer) } finally { writer.close() }}val file = new File("date.txt")withPrintWriter(file) { writer => writer.println(new java.util.Date)}