DJ180
DJ180

Reputation: 19854

Incorrect syntax for anonymous function

I need help trying to get my anonymous function to compile in Scala.

See below:

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

However, when I compile this I get "Expression of type block does not conform to expected"

What am I doing wrong here?

Upvotes: 0

Views: 61

Answers (1)

Akos Krivachy
Akos Krivachy

Reputation: 4966

The problem is that you're calling return block which is the returning to the mapBlock function the value block. But your mapBlock expectes a function typed (Any) => Block. To solve this just remove the return and have block.

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

If you want to have a return then you could name your function and return that. Although in Scala we generally omit all returns, so this would not be idiomatic Scala:

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

Upvotes: 4

Related Questions