scala> val upper1: String => String = _.toUpperCase
upper1: String => String = <function1>
scala> val upper2 = (x: String) => x.toUpperCase
upper2: String => String = <function1>
scala> def upper3: String => String = _.toUpperCase
upper3: String => String
scala> def upper4(x: String): String = { x.toUpperCase }
upper4: (x: String)String
scala> def upper5(x: String) = { x.toUpperCase }
upper5: (x: String)String
upper1和upper2都通过lambda函数方法定义函数,
只不过前者采用完整的lambda函数形式,后者采用了lambda函数的简写。
注意声明中=>发挥了不同的作用,
前者(以及upper3)中的=>用来分隔输入参数与返回值类型,
后者中的=>用来分隔参数列表与返回值表达式。
upper3, upper4和upper5都通过def关键字定义,
只是采取的不同的类型声明方式。
通过def定义的函数,只在被调用时(运行时)对函数体进行求值,每次被调用得到的函数实例都不同;
通过var定义的函数,在被定义后(运行时)立即被求值,每次被调用时使用了相同的函数实例。
参考:
What is the difference between def and val to define a function
How do you define a type for a function in Scala?