Home > Net >  Scala "illegal start of simple expression" when defining a function
Scala "illegal start of simple expression" when defining a function

Time:05-10

I am getting the following error on Scala:

scala> :pas
// Entering paste mode (ctrl-D to finish)

// sum takes a function that takes an integer and returns an integer then
// returns a function that takes two integers and returns an integer
def sum(f: Int => Int): (Int, Int) => Int =
  def sumf(a: Int, b: Int): Int = f(a)   f(b)
  sumf

// Exiting paste mode, now interpreting.

<pastie>:4: error: illegal start of simple expression
  def sumf(a: Int, b: Int): Int = f(a)   f(b)
  ^

I am not understanding why def is an illegal start of simple expression. I am simply trying to declare a function. Am I violating any syntax requirements in the declaration? Thank you.

UPDATE: This is my version of Scala:

sbt:jaime> console
[info] Starting scala interpreter...
Welcome to Scala 2.12.10 (OpenJDK 64-Bit Server VM, Java 11.0.14).
Type in expressions for evaluation. Or try :help.

scala>

CodePudding user response:

Two ways to make it work, as Luis Miguel Mejía Suárez mentioned in the comment to this question.

scala> :pas
// Entering paste mode (ctrl-D to finish)

def sum(f: Int => Int): (Int, Int) => Int = {
  def sumf(a: Int, b: Int): Int = f(a)   f(b)
  sumf
}

// Exiting paste mode, now interpreting.

sum: (f: Int => Int)(Int, Int) => Int

scala> :pas
// Entering paste mode (ctrl-D to finish)

def sum(f: Int => Int): (Int, Int) => Int = (a, b) => f(a)   f(b)

// Exiting paste mode, now interpreting.

sum: (f: Int => Int)(Int, Int) => Int

scala>
  • Related