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)
  }
   
}

你可能感兴趣的:(Scala的for、function)