scala 函数也是类
在scala中有一个function1的trait,
@annotation.implicitNotFound(msg = "No implicit view available from ${T1} => ${R}.")
trait Function1[@specialized(scala.Int, scala.Long, scala.Float, scala.Double/*, scala.AnyRef*/) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double/*, scala.AnyRef*/) +R] extends AnyRef { self =>
/** Apply the body of this function to the argument.
* @return the result of function application.
*/
def apply(v1: T1): R
/** Composes two instances of Function1 in a new Function1, with this function applied last.
*
* @tparam A the type to which function `g` can be applied
* @param g a function A => T1
* @return a new function `f` such that `f(x) == apply(g(x))`
*/
@annotation.unspecialized def compose[A](g: A => T1): A => R = { x => apply(g(x)) }
/** Composes two instances of Function1 in a new Function1, with this function applied first.
*
* @tparam A the result type of function `g`
* @param g a function R => A
* @return a new function `f` such that `f(x) == g(apply(x))`
*/
@annotation.unspecialized def andThen[A](g: R => A): T1 => A = { x => g(apply(x)) }
override def toString() = "<function1>"
}
在scala 的shell中,定义一个函数f,如下,其实就是继承了Function1

同时,函数类也是可以被继承的.
object MyTest extends (Int=>Int){
def apply(x:Int): Int ={
println(x+1)
x+1
}
def main(args: Array[String]) {
val test = MyTest(1)
}
}
输出2
posted on 2016-08-17 20:20 qiaoshi.wang 阅读(106) 评论(0) 收藏 举报
浙公网安备 33010602011771号