Scala本地函数


点击(此处)折叠或打开

  1. def main(args: Array[String]) {
  2.         val width = args(0).toInt
  3.         for (arg <- args.drop(1)) //取index==1的值
  4.          processData(arg, width) 
  5.         
  6.          var increase = (x: Int) => x + 1 //increase被赋值为一个匿名函数
  7.          println(increase(10))
  8.          increase = (x: Int) => x + 9999 //increase再被赋值
  9.         
  10.          val someNumbers = List(-11, -10, -5, 0, 5, 10)
  11.          someNumbers.foreach((x: Int) => print (x)) //自定义一个匿名函数
  12.          println
  13.          someNumbers.filter((x: Int) => x > 0).foreach((x: Int) => print (x))
  14.          println
  15.          someNumbers.filter((x) => x > 0).foreach((x: Int) => print (x))
  16.          println
  17.          someNumbers.filter(x => x > 0).foreach((x: Int) => print (x))
  18.          println
  19.          someNumbers.filter(_ > 0).foreach((x: Int) => print (x))
  20.          println
  21.          val f = (_: Int) + (_: Int) //函数也可以作为一个值
  22.          println(f(5, 10))
  23.     }
  24.     
  25.     def processData(filename: String, width: Int) {
  26.     
  27.      //本地函数-函数内部的函数,这种函数屏蔽了外部的访问
  28.      def processLine(line: String) {
  29.      if (line.length > width)
  30.          println(filename +": "+ line)
  31.      }
  32.     
  33.      val source = Source.fromFile(filename)
  34.      for (line <- source.getLines)
  35.          processLine(line)
  36.     
  37.     }

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28912557/viewspace-1849320/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/28912557/viewspace-1849320/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值