Scala的for、function

package com.sysu.jerry

import scala.io.Source

object For_Function_Advanced {
  def main(args: Array[String]):Unit = {
    
    //for函數
//    for(i <- 1 to 2; j <- 1 to 2) print((100*i + j) + " ")
//    println
    
    //for函數 終止條件
//    for(i <- 1 to 2;j <- 1 to 2 if i != j) print((100*i+j)+" ")
//        println
    
    //函數,一般可以不設置返回值,因爲可以自己判斷,但是斐波那契數列一定要
//    def addA(x:Int) = x + 100
//    val add = (x:Int) => x + 200
//    println("The result from a function is:" + addA(2))
//    println("The result from a val is:" + add(2))
    
    
    def fac(n:Int):Int = if(n<=0) 1 else n*fac(n-1)
    println("The result from a fac is : " + fac(4))
    
    
    //默認參數,也可以在使用函數的時候改變默認參數
    def combine(content:String,left:String = "[",right:String = "]") = left + content + right
    println("The resutl from a combine is : " + combine("I love you"))
    println("The resutl from a combine is : " + combine("I love you","<",">"))
    
    //可變參數  
    def connected(args:Int*) = {
      var result = 0
      for(arg <- args) result += arg
      result
    }
    println("The result from a connected is : " + connected(1,2,3,4))
    
    //lazy的聲明表示延遲執行,只有後面變量 實例化的時候才執行
    lazy val file = Source.fromFile("E:\\1.txt")   
    //println("Scala")
    
	  //for (line <- file.getLines) println(line)
  }
   
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章