def main(args : Array[String]): Unit = { def add(x:Int,y:Int):Int = { return x+y; } def subtract:(Int,Int)=>Int = (x,y)=>x-y; val multiply = (x:Int,y:Int)=>x*y; val division :(Int,Int)=>Float = (x,y)=>x/y; def sum:Int=>Int = i => i match { case 1 => 1; case n => n + sum(i-1); } def summ(i:Int):Int= i match { case 1 => 1; case n => n + summ(n-1); } lazy val fact:Int=>Int = { case 1 => 1; case n => n*fact(n-1); } lazy val summary:Int=>Int = (_:Int) match { case 1 => 1; case n => n + summary(n-1); } println(summ(100)); }
object Main{ def main(args:Array[String]):Unit= { object W { type S = String; type D = Tuple2[S,S]; def say(x:D):S= s"say ${x _1},${x _2}"; } implicit def MyStr(s:String)=new { def ++:(x:Char) = x + s; } val ss = 'c' ++: "hello"; // 相当于 "hello".++:('c') //但是如果写成 "hello" ++: 'c' 则提升 Char 没有 ++: 方法 Predef println ss } }
implicit def XString(s:String)= new { def unary_- = s.reverse; def ? = s.length; } println(-"hello");//olleh println( "hello"? );//5
在基类中将基本的操作(开\关\异常处理)都处理好,在子类中只定义功能操作.
package exp; import java.io.PrintWriter object Main { def main(args : Array[String]): Unit = { def fileOps = new MyFileOps; fileOps.opPw; } } class MyFileOps extends FileOps("/home/wengmj/1.txt") { override def pwOp(writer:PrintWriter):Unit=writer.println("hello world"); } abstract class FileOps(path:String) { def pwOp(writer:PrintWriter):Unit; def opPw():Unit= { val writer = new PrintWriter(path); try { this.pwOp(writer); } catch { case _:Throwable => println("unknow exception"); } finally { writer.close } } }
编写新的控制结构:借贷模式,柯里化
package exp import java.sql.SQLException object Main { def main(args: Array[String]): Unit = { val x = withDB(new DB()) {//这里本应该用小括号的用大括号是函数只有有个参数时用大括号更优美 db => {//这个大括号是定义函数必须的 db.prepareStatement("update products set product_name='aaa' where product_id=123"); db.update } } } def withDB(db: DB)(op: DB => Any): Any = { var r: Any = null; try { db.open r = op(db); db.close } catch { case e: Exception => println(e.getMessage); } finally { db.close } r; } } class DB { @throws(classOf[SQLException]) def prepareStatement(sql: String) = Unit; @throws(classOf[SQLException]) def open() = Unit; def close(): Unit = Unit; @throws(classOf[SQLException]) def update(): Boolean = false; }