标量函数组成-值,然后不是Int的成员

问题描述 投票:0回答:1

我正在尝试学习功能组成。我想将几种方法组成一个方法。

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
scala
1个回答
0
投票

andThen用于组成使用单个参数的两个函数。您的copyFile函数不带参数,因此无法以这种方式组合。

您可以通过给copyFile一个Unit参数来解决此问题:

val copyFile = (_: Unit) => {
  10
}

还请注意,copyFile andThen verifyCount不会调用任何一个函数,它只会创建一个新的复合函数,因此,如果您要进行任何操作,则必须调用该复合函数:

(copyFile andThen verifyCount)()
© www.soinside.com 2019 - 2024. All rights reserved.