Scala实战详解之第4讲 For与Function进阶实战、Lazy的使用

package com.dt.scalaInAction.demo_004

/**
 * For与Function进阶实战
 */
object For_Function_Advanced {
    def main(args: Array[String]): Unit = {
        for(i <- 1.to(2); j <- 1.to(2)) print((100*i+j)+" ")    //101 102 201 202
        println
        
        /**
         * for 表达式中的判断 可以加入复杂的条件表达式(重要)
         */
        for(i <- 1.to(2); j <- 1.to(2) if i != j) print((100*i+j)+" ")    //102 201
        println
      
      
      
      
      
      /**
       * 重要:在Scala中 函数时有值的 "="右边是对 怎么对函数进行计算   所以函数是可以作为参数进行传递的
       */
      def addA(x : Int) = x + 100       //def addA(x: Int): Int
      println("The result from a function is : " + addA(1))
      /**
       * "="的右侧其实是一个函数 (x : Int) => x + 100  这个函数没有名字是一个 匿名函数
       */
      val add = (x : Int) => x + 100    //val add: Int => Int
      println("The result from a val is : " + add(2))
      
      
      
      /**
       * 递归调用  在Scala中必须指明函数的返回值
       */
      def fac(n : Int) : Int = if(n <= 0) 1 else n * fac(n-1)
      println("The result from a fac is : " + fac(10))
      
      
      
      
      /**
       * 函数的默认值  param:type=vlaue
       */
      def combine(content : String,
                  left    : String = "{",
                  right   : String = "}") = left + content + right
      println("The result from a combine is : " + combine("I love you"))
      println("The result from a combine is : " + combine("I love you", "(^", "^)"))
      
      
      
      
      /**
       * 函数的参数是可变的 定义方式param:type*
       */
      def plus(x: Int*) = {
        var result = 0
        for (e <- x) result += e
        result
      }
      println("The result from a plus is : " + plus(1))
      println("The result from a plus is : " + plus(1,2,3,4,5))
      
      
    }
}





<pre name="code" class="plain">package com.dt.scalaInAction.demo_004

import scala.io.Source

/**
 * Lazy 延时加载
 */
object LazyOps {
    def main(args: Array[String]): Unit = {
//      val f = Source.fromFile("E:\\1.txt"); //由于路径不存在 导致异常 证明变量在定以后就会加载
      lazy val file = Source.fromFile("E:\\1.txt"); //lazy关键字 声明的变量只有在变量第一次使用的时候才会加载  证明是延时加载
      print("go")
    }
}


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值