匿名函数的语法不正确

时间:2013-11-23 18:52:12

标签: scala

我需要帮助尝试让我的匿名函数在Scala中编译。

见下文:

private def mapBlock(helper: Helper): (Any) => Block = {
    (original: Any) => {
      val block = original.asInstanceOf[Block]
      // logic with helper here
      return block
    }
  }

但是,当我编译它时,我得到“类型块的表达式不符合预期”

我在这里做错了什么?

1 个答案:

答案 0 :(得分:4)

问题是您正在调用return block,这是mapBlock函数返回值block。但是您的mapBlock预计会输入(Any) => Block个函数。要解决此问题,只需删除return并拥有block

private def mapBlock(helper: Helper): (Any) => Block = {
  (original: Any) => {
    val block = original.asInstanceOf[Block]
    // logic with helper here
    block
  }
}

如果您想拥有return,那么您可以命名您的功能并返回该功能。虽然在Scala中我们通常省略所有return s,所以这不是惯用的Scala:

private def mapBlock(helper: Helper): (Any) => Block = {
  val function = (original: Any) => {
    val block = original.asInstanceOf[Block]
    // logic with helper here
    block
  }
  return function
}