我正在尝试学习功能组成。我想将几种方法组成一个方法。
object mainApp {
val copyFile: () => Int = () => {
10
}
val verifyCount: (Int) => Unit = (cnt: Int) => {
assert(cnt == 10)
}
def main(args: Array[String]): Unit = {
verifyCount(copyFile)
copyFile andThen verifyCount
}
}
错误
value andThen is not a member of Int
copyFile andThen verifyCount
andThen
用于组成使用单个参数的两个函数。您的copyFile
函数不带参数,因此无法以这种方式组合。
您可以通过给copyFile
一个Unit
参数来解决此问题:
val copyFile = (_: Unit) => {
10
}
还请注意,copyFile andThen verifyCount
不会调用任何一个函数,它只会创建一个新的复合函数,因此,如果您要进行任何操作,则必须调用该复合函数:
(copyFile andThen verifyCount)()