Scala深入浅出实战经典:20,Scala中的本地函数与作为语言一等公民的函数详解

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)
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值