Scala深入浅出实战经典:20,Scala中的本地函数与作为语言一等公民的函数详解
2015-09-19 13:14
344 查看
package com.dt.scalaInAction.demo_020 import scala.io.Source /** * Scala中的本地函数与作为语言一等公民的函数详解 */ object FunctionOps { def main(args: Array[String]): Unit = { val width = args(0).toInt for(arg <- args.drop(1)) processData(arg, width) /** * 函数是有值的 函数可以赋值给变量 * (x: Int) => x+1 (x: Int)是匿名的 "=>"为函数的实现 */ var increase = (x: Int) => x+1 println(increase(5)) //row result: 6 //变量可以接受 其他函数值 increase = (x: Int) => x*2 println(increase(5)) //row result: 10 println("-----------------------------------") val someNumbers = List(-11, -10, -5, 0, 5, 10) someNumbers.foreach( (x: Int) => print(x + "\t") ) //row result:-11 -10 5 0 5 10 println() someNumbers.filter( (x: Int) => x > 0 ).foreach( (x: Int) => print(x + "\t") ) //row result:5 10 println() someNumbers.filter( (x) => x > 0 ).foreach( (x: Int) => print(x + "\t") ) //row result:5 10 println() someNumbers.filter( x => x > 0).foreach( (x: Int) => print(x + "\t") ) //row result:5 10 println() someNumbers.filter( _ > 0 ).foreach( (x: Int) => print(x + "\t") ) //row result:5 10 val f = (_: Int) + (_: Int) println() println(f(5, 10)) //row result: 15 } /** * 本地函数 line20-23 * (1) 本地函数所在的函数的外界不可以访问本地函数 * (2) 本地函数可以访问 所在函数传进来的参数 * * Scala中允许在函数中定义函数 定义的函数在私有函数 外界不可以访问 这样的函数被称之为"本地函数"也成为"内部函数" * 这样的做理由是因为 函数在Scala中是一等公明 函数可以看成变量一样 可以赋值 */ def processData(filename: String, width: Int) { //该函数为processData的私有函数 外部不可以访问 def processLine(line: String) { if (line.length > width) println(filename + ": " + line) } val source = Source.fromFile(filename) for(line <- source.getLines) processLine(line) } }
以上内容是从王家林老师DT大数据课程第20讲的学习笔记和个人整理。
DT大数据微信公众账号:DT_Spark
王家林老师QQ:1740415547
王家林老师微信号:18610086859
第20讲视频网站地址:http://pan.baidu.com/s/1kT3nIoZ
相关文章推荐
- Ubuntu14.04 工作区设置
- html框架
- react-redux(2)
- WPF 绘制图表
- POJ-1658
- android 数据库升级
- android事件传递机制的详细了解
- 腾讯面试经历2015
- Session
- Unity3d 人物白膜问题
- 图的历遍-深度优先历遍、广度优先历遍
- Android定调的发展
- Scala深入浅出实战经典:19,Scala中的正则表达式、与模式匹配结合的的Reg代码实战
- 八大排序算法
- nginx(五)nginx与php的安装配置
- diff
- Coursera_Stanford_ML_ex1 作业记录
- 实训以来的感受
- oracle 10g 创建数据库(手工)
- hdu 5077 NAND(暴力打表)