方法
scala> def hello(str: String): Unit = {
| println("hello" + str)
| }
hello: (str: String)Unit
scala> hello("world")
helloworld
scala> def m1(a: Int, b: Int):Int = {
| a * b
| }
m1: (a: Int, b: Int)Int
scala> m1(3,4)
res2: Int = 12
- 返回类型和等于号可以省略,当没有等于号时其默认的返回类型是Unit,即无值
scala> def hello(str: String) {
| println("hello" + str)
| }
hello: (str: String)Unit
scala> hello("there")
hellothere
scala> def m1(a: Int, b: Int) = {
| a * b
| }
m1: (a: Int, b: Int)Int
scala> m1(3,9)
res5: Int = 27
scala> def m1(a: Int, b: Int) {
| a * b
| }
m1: (a: Int, b: Int)Unit
scala> m1(3, 4)
函数(如有错误敬请指正)
- 函数是scala的一等公民,可以使用在任何地方,可以赋值给一个变量,可以作为一个方法的参数,也可以作为一个函数的参数,其实方法也可以作为一个方法的参数或者函数的参数。scala中的任何对象,方法,函数都可以作为参数。
scala> val f1 = (x: Int, y: Int) => {
| x + y
| }
f1: (Int, Int) => Int = <function2>
scala> f1(3,7)
res6: Int = 10
scala> val f1 = (x: Int, y: Int) => x + y
f1: (Int, Int) => Int = <function2>
scala> f1(3,8)
res7: Int = 11
scala> def m1(m: (Int, Int) => Int) = {
| m(3, 10)
| }
m1: (m: (Int, Int) => Int)Int
scala> m1(f1)
res8: Int = 13
scala> val f2 = (x:Int, y:Int) => x * y
f2: (Int, Int) => Int = <function2>
scala> m1(f2)
res9: Int = 30
scala> def m1(m: (Int, Int) => Int, a:Int, b:Int) = {
| m(a, b)
| }
m1: (m: (Int, Int) => Int, a: Int, b: Int)Int
scala> m1(f1, 3, 11)
res12: Int = 14
scala> val arr = Array(1, 3, 5)
arr: Array[Int] = Array(1, 3, 5)
scala> val f1 = (x: Int) => x * 2
f1: Int => Int = <function1>
scala> arr.map(f1)
res10: Array[Int] = Array(2, 6, 10)
scala> val function = (x:Int, y:Int) => {
| x + y
| }
function: (Int, Int) => Int = <function2>
scala> def method(x:Int,y:Int) = {
| x * y / 3
| }
method: (x: Int, y: Int)Int
scala> val function1 = (operator:(Int,Int) => Int) => {
| operator(10, 11);
| }
function1: ((Int, Int) => Int) => Int = <function1>
scala> def method1(operator:(Int,Int) => Int) = {
| operator(10, 11)
| }
method1: (operator: (Int, Int) => Int)Int
scala> function1(function)
res1: Int = 21
scala> function1(method)
res2: Int = 36
scala> method1(function)
res3: Int = 21
scala> method1(method)
res4: Int = 36
- 经过以上测试,scala中的函数和方法是可以通用的。我觉的scala中之所以还要区分函数和方法,是因为在OOP编程中一个类的行为要用方法去定义。