Scala:Function1、Function2

Function1

带一个参数的方法,声明时,它需要两个泛型参数,第一个是传入的数据类型,第二个表示返回的数据类型,Function1是 trait ,它有一个apply方法,用来对输入参数进行处理了,使用Function1,必须实现apply接口

val funs = new Function1[Int,Int] {
  def apply(x:Int) = {
    x + 1
  }
}

//使用
println(funs.apply(5))      // 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

andThen

和另一个Function1实例组合成一个新的Function1实例,当前这个方法先执行,执行完的结果作为另一个方法的入参

    val funs = new Function1[Int,Int] {
      def apply(x:Int) = {
        println("第一步:"+x)
        x + 1
      }
    }
    val succ = (x: Int) => {
      println("第二步:"+x)
      x + 3
    }
    println(succ.andThen(funs).apply(5))
    /**
    第二步:5
    第一步:8
    */
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

compose

与andThen相反,同样是组合成新的Function1,但是作为参数的那个Function1先执行

//依然执行这个打印过程
println(succ.compose(funs).apply(5))
/**
第一步:5
第二步:6
*/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Function2

带两个参数的方法,它的声明需要三个泛型参数,前两个是入参类型,第三个是返回数据类型,同Function1一样,也要实现apply方法

val funs = new Function2[Int,Int,Int] {
  def apply(x:Int,y:Int) = {
    x + y
  }
}
println(funs.apply(1,2))    //  3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

curried

为当前方法创建一个柯里化的版本

val funs = new Function2[Int,Int,Int] {
  def apply(x:Int,y:Int) = {
    x + y
  }
}
val curryfun = funs.curried
println(curryfun(1)(2))     //  3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

tupled

为当前方法创建一个tupled(元组)版本

val funs = new Function2[Int,Int,Int] {
  def apply(x:Int,y:Int) = {
    x + y
  }
}
val tupledfun = funs.tupled
println(tupledfun((1,2)))

猜你喜欢

转载自blog.csdn.net/bbbeoy/article/details/80829559
今日推荐