1. 程式人生 > >SCALA的例子詳解

SCALA的例子詳解

scala是一門函式式的面向物件的語言,它執行在java虛擬機器上。
eg1、
示例程式碼:
scala>var helloWorld = "hello" + " world" 
println(helloWorld)scala>val again = " again" 
helloWorld = helloWorld + again
println(helloWorld)
輸出:
hello world
hello world again
eg2、定義函式 def
示例程式碼:
def square(a: Int) = a * adef squareWithBlock(a: Int) = { a * a}
val squareVal = (a: Int) => a * a (這裡是將Int整數a對映為a*a的函式)def addOne(f: Int => Int, arg: Int) = f(arg) + 1(這裡的=>表示所對映的型別,這就表示這個引數要是一個引數為int型別,返回的型別也是int 的方法)println("square(2):" + square(2)) println("squareWithBlock(2):" + squareWithBlock(2)) println("squareVal(2):" + squareVal(2)) println("addOne(squareVal,2):" + addOne(squareVal, 2))
輸出結果: square(2):4 squareWithBlock(2):4 squareVal(2):4 addOne(squareVal,2):5 eg3、 程式碼例項: import scala.reflect.io.File import java.util.Scannerdef withScanner(f: File, op: Scanner => Unit) = {// 沒有返回值的預設返回的是Unit     val scanner = new Scanner(f.bufferedReader)     try {         op(scanner)     } finally {
        scanner.close()     } }withScanner(File("/proc/self/stat"),     scanner => println("pid is " + scanner.next())) 其中widthScanner封裝了try-Catch塊,呼叫者不用再close了 返回結果: pid is 6065 eg4、定義類 class Persion(val firstName: String, val lastName: String) {  //通過class定義類,val來定義欄位,在類中def定義類中的函式,其中firstName和lastName會自動生成get,set方法    private var _age = 0     def age = _age  //這是一個方法     def age_=(newAge: Int) = _age = newAge    def fullName() = firstName + " " + lastName    override def toString() = fullName()//這是覆蓋toString方法 }val obama: Persion = new Persion("Barack", "Obama")//用new的方式建立類println("Persion: " + obama) println("firstName: " + obama.firstName) println("lastName: " + obama.lastName) obama.age_=(51) println("age: " + obama.age) 返回結果: Persion: Barack Obama firstName: Barack lastName: Obama age: 51 eg5、 執行例項: def withClose(closeAble: { def close(): Unit }, //這裡是將{def close():Unit}這個方法作為一種型別     op: { def close(): Unit } => Unit) {     try {         op(closeAble)     } finally {         closeAble.close()     } }class Connection {     def close() = println("close Connection") }val conn: Connection = new Connection() withClose(conn, conn =>     println("do something with Connection")) 執行結果: do something with Connection close Connection eg6、柯里化(currying)技術 def add(x:Int, y:Int) = x + y是普通的函式 def add(x:Int) = (y:Int) => x + y 是柯里化後的函式,相當於返回一個匿名函式表示式。 def add(x:Int)(y:Int) = x + y 是簡化寫法
def withClose(closeAble: { def close(): Unit })//小白一枚,還是沒有弄明白為什麼我建立這個方法時候總是無效的???
    (op: { def close(): Unit } => Unit) {
    try {
        op(closeAble)
    } finally {
        closeAble.close()
    }
}
class Connection {
    def close() = println("close Connection")
}
val conn: Connection = new Connection()
withClose(conn)(conn =>
    println("do something with Connection"))
eg7、泛型
def withClose[A <: { def close(): Unit }, B](closeAble: A)//這裡的A表示的是{def close():Unit}的子型別
  (f: A => B): B =
  try {
    f(closeAble)
  } finally {
    closeAble.close()
  }
class Connection {
  def close() = println("close Connection")
}
val conn: Connection = new Connection()
val msg = withClose(conn) { conn =>
  {
    println("do something with Connection")
    "123456"
  }
}
println(msg)
返回結果:
do something with Connection
close Connection
123456
eg8 Traits 相當於java中的介面implements
trait ForEachAble[A] {
  def iterator: java.util.Iterator[A]
  def foreach(f: A => Unit) = {
    val iter = iterator
    while (iter.hasNext)
      f(iter.next)
  }
}
trait JsonAble {
  def toJson() =
    scala.util.parsing.json.JSONFormat.defaultFormatter(this)
}
val list = new java.util.ArrayList[Int]() with ForEachAble[Int] width JsonAble 
list.add(1); list.add(2)
println("For each: "); list.foreach(x => println(x))
//println("Json: " + list.toJson())