编译:
def fibonacci():() => Int = {
var first = 1
var second = 2
return () => {
val oldFirst = first
first = second
second = second + oldFirst
second
}
}
这不是:
def fibonacci():() => Int = {
var first = 1
var second = 2
return ():Int => {
val oldFirst = first
first = second
second = second + oldFirst
second
}
}
我明确地试图告诉它我正在返回一个Int,但我收到此错误:Illegal start of declaration
,它指向first = second
行。他们有什么不同?我使用的是Scala 2.8.1。
答案 0 :(得分:8)
return (): Int => {...}
在Scala中不是一个正确的表达式。如果要明确指定返回类型,则需要在之后放置声明(并且值将是匿名函数):
def fibonacci():() => Int = {
var first = 1
var second = 2
return ( () => {
val oldFirst = first
first = second
second = second + oldFirst
second
} ) : () => Int
}
但请注意,没有必要这样做。如果省略return
,则根本不需要进行任何明确的类型声明:
def fibonacci() = {
var first = 1
var second = 2
() => {
val oldFirst = first
first = second
second = second + oldFirst
second
}
}
答案 1 :(得分:6)
Debilski是对的。还有两条评论:(1)return
关键字不是必需的。默认情况下,最后一个表达式成为返回值。 (2)如果你试图单独注释函数体的类型,那是可能的。代码变为:
def fibonacci2(): () => Int = {
var first = 1
var second = 2
() => {
val oldFirst = first
first = second
second = second + oldFirst
second
}: Int
}