提问人:linrongbin 提问时间:7/29/2020 更新时间:7/29/2020 访问量:55
为什么我的 scala 函数/闭包定义是非法的?[已结束]
Why my scala function/closure definition is illegal? [closed]
问:
我正在学习 scala 编程语言。
这里有一些简单的功能和带有错误的闭包,请帮我修复它们:Rational.scala
// function
def f11(a:Int, b:Int):Int { return a+b; }
def f12(a:Int, b:Int):Int = a+b
def f21(a:(Int)=>Int, b:Int):Int { return a(b); }
def f22(a:(Int)=>Int, b:Int):Int = a(b)
def f31(a:Int, b:Int):(Int)=>Int { return (c:Int) => a + b + c; }
def f32(a:Int, b:Int):(Int)=>Int = (c:Int) => a + b + c
// closure
val g11 = (a:Int, b:Int) => a + b;
val g12:(Int,Int)=>Int = (a:Int, b:Int) => { return a + b; }
val g21 = (a:(Int)=>Int, b:Int) => a(b);
val g22:((Int)=>Int,Int)=>Int = (a:(Int)=>Int, b:Int) => { return a(b); }
val g31 = (a:Int, b:Int) => (c:Int) = a+b+c;
val g32:(Int,Int)=>(Int)=>Int = (a:Int, b:Int) => { return (c:Int) => a+b+c; }
运行它们时,给我错误消息:scala Rational.scala
Rational.scala:32: error: illegal start of declaration (possible cause: missing `=` in front of current method body)
def f11(a:Int, b:Int):Int { return a+b; } // (Int,Int)->Int
^
Rational.scala:36: error: illegal start of declaration (possible cause: missing `=` in front of current method body)
def f21(a:(Int)=>Int, b:Int):Int { return a(b); } // ((Int)->Int,Int)->Int
^
Rational.scala:40: error: illegal start of declaration (possible cause: missing `=` in front of current method body)
def f31(a:Int, b:Int):(Int)=>Int { return (c:Int) => a + b + c; } // (Int,Int)->(Int)->Int
^
Rational.scala:54: error: ';' expected but '=' found.
val g31 = (a:Int, b:Int) => (c:Int) = a+b+c;
答:
4赞
John K
7/29/2020
#1
错误消息非常清楚,与大多数其他定义不同,您只是在函数主体之前缺少一个相等。
例如
def f11(a:Int, b:Int):Int { return a+b; }
应该成为
def f11(a:Int, b:Int):Int = { return a+b; }
此外,在 Scala 中,闭包的值会自动是最新计算的值,并且可能不会像您想象的那样执行。所以正确的定义应该是return
def f11(a:Int, b:Int):Int = {
a+b
}
评论