scala学习笔记4

函数和闭包
1.定义函数最通用的方法是作为某个对象的成员,这种函数被称为方法。
2.函数式编程风格:程序应该被解构成若干小的函数,每块实现一个定义完备的任务,组装成复杂的事物
3.局部函数可以定义在另外一个函数的内部,并且局部函数可以访问外部函数的属性
4.=>指明函数左边的东西转化成右边的东西
5.什么叫闭包:
  一直一个函数f(x) = x + i ,让你求f(3) = 3 + i。
  分析:要得到最终的函数值,你必须知道i的值。i称作开放项。
     若上文中定义了 int i = 1 ,则可以得到f(3) = 3 + 1 = 4.
     即函数值若想捕获i的值,这一过程被理解为做对函数执行“关闭”操作,所以叫闭包
6.scala的函数是头等函数

package com.scala.stu
import scala.io.Source
/**
 * 函数和闭包
 */
object t_007 {
  
  def main(args: Array[String]): Unit = {
   /*
   * =>指明函数左边的东西转化成右边的东西
   */
  var increase = (x: Int) =>  {//{}代表代码块
    println("this is one line")
    x + 1
  }
  println(increase(10))//变量可以通过这种形式进行重新赋值,因为任何函数值都是扩展了若干的function的
  
  
  var someNumbers = List(-11,-10,-5,0,5,10)
  //filter,这个方法选择集合类型里可以通过用户提供的测试的元素
  someNumbers = someNumbers.filter { x =>x > 0 }
  //_是占位符
  someNumbers = someNumbers.filter { _ > 0 }
  //foreach,每个集合类都能用的foreach方法,定义在特质Iterable中他是list,set,array,map的共有的超特质
  someNumbers.foreach { x => print(x+" ") }
  someNumbers.foreach { println _}
  //_+_ 将扩展成带两个参数的函数字面量,多个下划线代表多个参数
  //只有在需要函数类型的地方,scala才允许你省略这个仅用的_
  val f = (_: Int) + (_: Int)
  println(f(1,2))
  }
  
  //本地函数
  def processFile(filename: String , width: Int) {
    
      def processLine(line: String){
        println(filename + " :" + line.trim)
    }
      /*
       * def processLine(filename: String,width: Int , line: String){
        println(filename + " :" + line.trim)
   			 }
       */
    val source = Source.fromFile(filename)
    for (line <- source.getLines)//getLines返回枚举类型
    processLine(line)
  }
  
  //柯里化
  def curr(x: Int)(y: Int) = x+y
  def first(x:Int) = (y:Int) =>x + y
  
  
  
  
}

猜你喜欢

转载自see-you-again.iteye.com/blog/2257110