Scala "illegal start of simple expression" 定义函数时
Scala "illegal start of simple expression" when defining a function
我在 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)
^
我不明白为什么 def
是 illegal start of simple expression
。我只是想声明一个函数。我是否违反了声明中的任何语法要求?谢谢。
更新:这是我的 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>
正如 Luis Miguel Mejía Suárez 在对此问题的评论中提到的那样,有两种方法可以使其发挥作用。
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>
我在 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)
^
我不明白为什么 def
是 illegal start of simple expression
。我只是想声明一个函数。我是否违反了声明中的任何语法要求?谢谢。
更新:这是我的 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>
正如 Luis Miguel Mejía Suárez 在对此问题的评论中提到的那样,有两种方法可以使其发挥作用。
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>