scala函数和闭包
2020-05-02 本文已影响0人
平头哥2
Function and closure
//1. method
def processFile(filename: String, width: Int): Unit = {
val source = Source.fromFile(filename)
for( line <- source.getLines())
processLine(filename, width, line)
}
def processLine(filename : String,width: Int, line:String): Unit ={
if(line.length > width)
println(filename +" : "+ line.trim)
}
//2. local function
def processFile(filename: String, width: Int): Unit = {
def processLine(line:String): Unit ={
if(line.length > width)
println(filename +" : "+ line.trim)
}
val source = Source.fromFile(filename)
for( line <- source.getLines())
processLine(line)
}
//3. 函数
/**
* function and closure
*
* scala 的函数时头等公民
* 1. 不仅仅是 函数可以定义和调用
* 2. 函数可以写为一个 函数字面量 并且作为值进行传递
*
* 函数字面量 在编译阶段会被编译为一个类,在运行阶段会被初始化为一个函数值
* 区别:
* 函数字面量 存在于源码中
* 函数值: 作为一个对象存在于运行时
*
*/
object FunDemo {
def main(args: Array[String]): Unit = {
//函数字面量的定义
(x: Int) => x+1
}
}
//函数字面量定义
scala> var inc = (x : Int) => x+2
inc: Int => Int = $$Lambda$776/733224796@24c685e7
//使用
scala> inc(3)
res0: Int = 5
//函数字面量的定义
val inc = (x: Int) => x + 1
println(inc(2))
//案例
val someNumbers = List(-11, -10, -5, 0, 5, 10)
someNumbers.foreach((x: Int) => print(x+" ")) //-11 -10 -5 0 5 10
val gt = someNumbers.filter((x: Int) => x > 3)
println(gt) //List(5, 10)
//化简
someNumbers.foreach(x => print(x+" "))
val gt2 = someNumbers.filter(x => x > 3) // List(5, 10)
// PLACEHOLDER SYNTAX
someNumbers.foreach( _ => print _)
someNumbers.foreach(print _)
someNumbers.foreach(print)
val gt3 = someNumbers.filter( _ > 3)
//案例
val f = (_: Int) + (_: Int)
println(f(1,2))
object FunDemo {
def main(args: Array[String]): Unit = {
//案例
val someNumbers = List(-11, -10, -5, 0, 5, 10)
//someNumbers.foreach(print _) //print _ 其实是一个部分应用函数
val res = sum _
val b = res(1, _: Int, 3)
println(b(2)) // 这里实际调用b.apply, 进而调用了sum(1,2,3)
//闭包
val more = 1
val addMore = (x: Int) => x + more
println(addMore(3))
//可变参数
def fun(arr: String*): Unit = {
arr.foreach(println)
}
fun("a", "b", "c")
val arr = Array("aa", "bb", "cc")
fun(arr: _*)
//带名字参数
def fun02(time: Int, s: Float): Float = {
s / time
}
println(fun02(s = 100.0F, time = 10)) //10.0
//缺省参数
def fun03(out: java.io.PrintStream = Console.out): Unit = {
out.println("time "+ System.currentTimeMillis())
}
fun03()
}
def sum(a: Int, b: Int, c: Int): Int = {
a + b + c
}
}