场景
匿名函数的语法与常用使用方式、高阶函数初体验
实验
package com.scode.scala
import scala.io.Source
/**
* author: Ivy Peng
* function: 1、学习匿名函数作为函数参数的使用方式
* 2、了解函数内部定义函数-实现高内聚、低耦合
* 3、高阶函数-初体验:多重嵌套
* date:2016/03/09 23.36
* sum:
* 匿名函数语法:(arg:argType,...)=> operations 。
*/
object FunctionOps
{
def main(args:Array[String]):Unit =
{
val width = args(0).toInt
for(arg<-args.drop(1))
processData(arg, width)
functionChild
println(high_order_fun2(scala.math.ceil _))
}
/**
* 匿名函数语法:(arg:argType,...)=> operations
* 若参数只有一个,则可以简写成 arg =>operations
*/
def functionChild()
{
var increase=(x:Int)=>x+10 //匿名函数(),方法体只有一行,用 => 链接起来
println(increase(10))
increase=(x:Int)=>x+100
val someNums = List(-1,2,3,0)
someNums.foreach((x:Int)=>print(x+" "))
println
someNums.filter((x:Int)=>x>0).foreach(x=>println(x+" "))
someNums.filter((x)=>x>0).foreach(x=>println(x+" "))
someNums.filter(x=>x>0).foreach(x=>println(x+" "))
val f = (_: Int)+(_: Int)
println(f(5,10))
}
/**
* 高内聚低耦合
*/
def processData(filename:String , width:Int)
{
def processLine(line:String) =
{
if(line.length>width)
{
println(filename+":"+line)
}
}
val file = Source.fromFile(filename);
for(line<-file.getLines)
{
processLine(line)
}
}
/**
* 高阶函数-初体验
*/
def high_order_fun()
{
(1 to 9).map("*" * _).foreach(println _)
(1 to 9).filter(_%2 ==0).foreach(println)
println((1 to 4).reduceLeft(_*_))
"you are my sunshine ,my only sunshine".split(" ").
sortWith(_.length<_.length).foreach(println)
val fun = scala.math.ceil _;
val num = 3.14
println(fun(num))
Array(2,3.3,4.3).map(fun).foreach(println _)
}
/**
* 高阶函数:函数作为函数的参数
* 注:(Double)=>Double : 对函数的参数(Double型)不做处理
*/
def high_order_fun2(f:(Double)=>Double) = f(0.29)
}
参考文献
scala 深入浅出实战经典 . 王家林