定义函数

如果定义的时候没有加(),那么调用的时候也不能加()

函数其实在scala就是个对象,我们可以用个变量来引用他

  1. scala> val f1 = (x:Int, y:Int) => x+y
  2. f1: (Int, Int) => Int = $$Lambda$1068/185209393@4833eff3
  3. scala> f1(1,2)
  4. res1: Int = 3

完整定义的函数

  1. scala> val f3:(Int, Double) => (Double, Int) = {(x:Int, y:Double) => (y,x)}
  2. f3: (Int, Double) => (Double, Int) = $$Lambda$1086/1751080205@3830b06c
  3. scala> f3(1, 1.3)
  4. res2: (Double, Int) = (1.3,1)

变长函数

  1. println(sum(1, 2, 3))
  2. def sum(args: Int*) = {
  3. var result = 0
  4. for (arg <- args) {
  5. result += arg
  6. }
  7. result
  8. }