王家林亲传《DT大数据梦工厂》第四讲For与Function进阶实战、Lazy的使用

来源:互联网 发布:疯狂美工京东装修助手 编辑:程序博客网 时间:2024/05/17 22:05

王家林亲传《DT大数据梦工厂》第四讲For与Function进阶实战、Lazy的使用

你想了解大数据,你想成为年薪百万吗?那你还等着什么,快点来吧!跟着王家林老师学习spark大数据

第四讲For与Function进阶实战、Lazy的使用

For循环

objectFor_Function_Advanced{

def  main ( args:Array[String]): Unit ={

      for(i  <- 1 to 2;j <-  1 to2)print((100*i + j) + “ ”)

printIn

     for(i  <- 1 to 2;j <-  1 to 2 if i!=j)print((100*i + j) + “ ”)//添加条件表达式

printIn

函数

def  addA(x : Int)  =  x+100

val add  = (x : Int)  => x+200\\匿名函数

printIn(“The result from a function is :” + addA(2))

printIn(“The result from a val is :” + add(2))

Scala特点:函数是有值得;可以作为函数的参数去传递

Def fac(n:Int):Int   =  if ( n <= 0)  1 else n * fac(n - 1)

printIn(“The result from a fac is : ”  + fac(10))

递归算法的函数要有返回值类型

函数参数默认值

def combine(content:String, left:String  = “[“,right:String = “]”)   =left + content +right

printIn(“The result from a combine is :” +combine (“ I love Spark))

函数的参数是可变的

def connected(args:Int*) = {

var result =0

for(arg <- args) result +=arg

result

}

printIn(“The result from a connected is :” +connected(1,2,3,4,5))

Lazy使用

object LazyOps {

   def main (args:Array[String]): Unti = {

   lazy val file =Source.fromFile(“F:\\tuiguangneirong1.docx”)

  printIn(“Scala”)

for( line <- file.getLines)printIn(line)

}

     }

//Lazy 第一次使用的时候才实例化;延迟执行,懒执行,对同一个数据处理有迭代的计算

通过简单代码示例,从基础了解For循环,和For循环以后常用的方式(带有条件表达式)与Function基本(递归算法的函数要有返回值类型

和Scala的小特点:函数是有值得;可以作为函数的参数去传递)、Lazy的使用。希望自己跟着老师学习一点一点进步;

如果你了解的还是不清楚,你也可以学习此视频或者是记录一下联系方式

 视频地址:http://www.tudou.com/programs/view/ge646hSN8tc/

学习地址:http://mp.weixin.qq.com/s?__biz=MzAwNjAwODI3Mg==&mid=212579488&idx=2&sn=883193df2b3df163d49c4fdec1ecd585&scene=5#rd

0 0