我试图在Scala shell中定义以下函数,它接受3个独立的函数作为参数,然后调用这些函数: -
def myfun(f1:(Int)=>Unit,f2:(Int,Int)=>Unit,f3:(Int,Int,Int)=>Unit) = f1(1); f2(1,2); f3(1,2,3)
Scala shell抛出错误说: -
<console>:22: error: not found: value f3
f3(1,2,3)
^ <console>:20: error: not found: value f2
def myfun(f1:(Int)=>Unit,f2:(Int,Int)=>Unit,f3:(Int,Int,Int)=>Unit) = f1(1); f2(1,2);;
但是如果我在函数体中的不同行上调用这些函数,它就可以完美地运行: -
scala> def myfun(f1:(Int)=>Unit,f2:(Int,Int)=>Unit,f3:(Int,Int,Int)=>Unit) = {
| f1(1)
| f2(1,2)
| f3(1,2,3)
| }
myfun: (f1: Int => Unit, f2: (Int, Int) => Unit, f3: (Int, Int, Int) => Unit)Unit
我读到的是scala支持在同一行上调用多个函数,只要它们用分号分隔即可。那为什么这表现不同?
答案 0 :(得分:2)
将它们包裹在一个区块中:
... = { f1(1); f2(1,2); f3(1,2,3) }
您拥有的代码相当于:
def myfun(f1: (Int) => Unit, f2: (Int, Int) => Unit, f3: (Int, Int, Int) => Unit) = f1(1)
f2(1, 2)
f3(1, 2, 3)