4,For与Function进阶实战、Lazy的使用

package com.dt.scala.hello

object For_Function_Advanced {

  def main(args: Array[String]): Unit = {
    for (i <- 1 to 2; j <- 1 to 2) print((100 * i + j) + "  ")
    println
    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(10))

    def combine(content: String, left: String = "[", right: String = "]") = left + content + right
    println("The result from a combine is : " + combine("I love Spark", "<<"))

    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, 5, 6))
  }
}

package com.dt.scala.hello

import scala.io.Source

object LazyOps {

  def main(args: Array[String]): Unit = {
    // 第一次被使用的时候用才被实例化
    lazy val file = Source.fromFile("E:\\SparkWangJialin.txt")

    println("Scala")
    //	for (line <- file.getLines) println(line)
  }
}

信息来源于 DT大数据梦工厂微信公众账号:DT_Spark

网址:http://pan.baidu.com/share/home?uk=4013289088&view=share#category/type=0


你可能感兴趣的:(4,For与Function进阶实战、Lazy的使用)