模式比對使用提取器:
當一個類的執行個體後跟括弧使用零個或多個參數的列表,所述編譯器調用應用的方法在該執行個體上。我們可以定義同時適用對象和類。
如上述所提到的,unapply方法的目的是提取我們尋找一個特定的值。它相反的操作和apply一樣。當比較使用匹配語句中unapply方法的提取對象將被自動執行,如下所示:
object Test {
def main(args: Array[String]) {
val x = Test(5)
println(x)
x match
{
case Test(num) => println(x+" is bigger two times than "+num)
//unapply is invoked
case _ => println("i cannot calculate")
}
}
def apply(x: Int) = x*2
def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}
讓我們編譯和運行上面的程式,這將產生以下結果:
C:/>scalac Test.scala
C:/>scala Test
10
10 is bigger two times than 5
C:/>
Scala開啟檔案是利用Java對象和java.io.File,它們都可在Scala編程中用來讀取和寫入檔案。以下是寫入檔案的一個例子:
import java.io._
object Test {
def main(args: Array[String]) {
val writer = new PrintWriter(new File("test.txt" ))
writer.write("Hello Scala")
writer.close()
}
}
當上面的代碼被編譯和執行,它會建立一個有“Hello Scala”內容的檔案。
C:/>scalac Test.scala
C:/>scala Test
C:/>
從螢幕讀取一行:
有時需要從螢幕上讀取使用者輸入,然後進行某些進一步的處理。下面的例子說明了如何從螢幕上讀取輸入:
object Test {
def main(args: Array[String]) {
print("Please enter your input : " )
val line = Console.readLine
println("Thanks, you just typed: " + line)
}
}
當上面的代碼被編譯和執行,它會提示輸入內容,並繼續進行,直到按ENTER(斷行符號)鍵。
C:/>scalac Test.scala
C:/>scala Test
scala Test
Please enter your input : Scala is great
Thanks, you just typed: Scala is great
C:/>
讀取檔案內容:
從檔案中讀取是非常簡單的。可以使用Scala的Source 類和它配套對象讀取檔案。以下是這些顯示如何從之前建立“test.txt”檔案中讀取內容的樣本:
import scala.io.Source
object Test {
def main(args: Array[String]) {
println("Following is the content read:" )
Source.fromFile("test.txt" ).foreach{
print
}
}
}
當上述代碼被編譯和執行時,它將讀取test.txt檔案並在螢幕上顯示內容:
C:/>scalac Test.scala
C:/>scala Test
scala Test
Following is the content read:
Hello Scala
C:/>from: http://www.yiibai.com/scala/scala_basic_syntax.html