Scala基礎教程(九):提取器、檔案I/O_Scala

來源:互聯網
上載者:User
模式比對使用提取器:

當一個類的執行個體後跟括弧使用零個或多個參數的列表,所述編譯器調用應用的方法在該執行個體上。我們可以定義同時適用對象和類。

如上述所提到的,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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.