20.Scala中本地函数与作为语言一等公民的函数详解

一、本地函数代码实战

package ce.scala.pp

import scala.io.Source

object FunctionOps_20 {
  def main(args: Array[String]): Unit = {
     
   val width = args(0).toInt
   for(arg <- args.drop(1))  //F:\lili
     processData(arg, width)
   
  }
  
  //对于模块封装,强内聚弱耦合是至关重要的。而内部函数就可以实现这个要求
  def processData(filename : String , width : Int){

   def processLine(line : String){  //内部函数(本地函数) 
      if(line.length > width)   //内部函数可以访问外部函数传入的参数width
        println(filename + " : " + line)
    }
    
    var source = Source.fromFile(filename)
    for(line <- source.getLines)
      processLine(line)
    
  }
}

F:\lili.txt文件里有三句话:

I feel
I am into Music so much!!!
SS


输出:

F:\lili.txt : I feel
F:\lili.txt : I am into Music so much!!!

二、作为一等公民的函数代码实战

  var increase = (x : Int) => x + 1  //匿名函数,把这个函数作为值赋值给变量increase
  println(increase(10))  //输出11
  
  increase = (x : Int) => x +9999   //这个变量increase又可以被赋值为其他函数 val someNumbers = List(-11, -10, -5, 0, 5, 10)
 


    val someNumbers = List(-11, -10, -5, 0, 5, 10)
    someNumbers.foreach { (x : Int) => print(x+ " ") }  //输出-11 -10 -5 0 5 10 

    println
    someNumbers.filter( (x : Int) => x > 0 ).foreach{ (x : Int) => print(x+ " ")}  //输出 5 10 
    println
    someNumbers.filter { (x) => x >0 }.foreach{(x : Int) => print(x+ " ")}  //输出 5 10  可以省略掉参数类型Int
    println
    someNumbers.filter { x => x >0 }.foreach{(x : Int) => print(x+ " ")}  //输出 5 10  对于只有一个参数的函数,可以省略掉参数外围的括号()
    println
    someNumbers.filter { _ >0 }.foreach{(x : Int) => print(x+ " ")}  //输出 5 10   如果参数x在=>右侧只出现一次,则可以用下划线_替换掉
    println


   val f = (_:Int) + (_:Int)  //匿名函数
  println(f(3,8))  //输出:  11

请仔细看每个filter里的变化。x的类型Int可以去掉 ==> x括号可以去掉 ==> 若只有一个参数,可以用下划线_代替


参考资料来源于 DT大数据梦工厂Scala零基础实战经典第20课 由王家林老师讲解



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值