简体   繁体   English

为什么不能在Scala中为匿名函数指定结果类型?

[英]Why can't I specify a result type for an anonymous function in Scala?

Edit: Found the answer, see end of post. 编辑:找到答案,请参阅文章结尾。

kept getting errors, found it was because I was trying to add result types to lambdas. 不断出现错误,发现这是因为我试图将结果类型添加到lambda。 This is fine 这可以

(p: Int) => p

whereas

(p: Int): Int => p

causes it complaints. 引起投诉。 I'm surprised - why not allow it? 我很惊讶-为什么不允许呢? After all I can specify a type in the variable (I've bracketed the type for readability) if I assign the lambda: 毕竟,如果我分配了lambda,我可以在变量中指定一种类型(为了便于阅读,我将其放在括号中):

val f2: (Int => Int) = (p: Int) => p

but then I might as well def it: 但当时我还不如def它:

def f2(p: Int): Int = p

I can't see any obvious harm in disallowing it, but it is unexpected. 禁止使用它不会带来任何明显的危害,但这是意外的。 Thoughts? 有什么想法吗?


Edit: Stone me, you can: 编辑:给我扔石头,您可以:

(p: Int) => p : Int

OK, answered. 好,回答。 Never seen that before. 以前从未见过。 I guess I'll leave this here for posterity. 我想我将在这里留给后代参考。

Per suggestion of 0__, the answer is to suffix the body of the lambda with the type, not put it after the parameter list as would be suggested by the def syntax. 根据0__的建议,答案是给lambda的主体加上类型的后缀,而不是像def语法所建议的那样将其放在参数列表之后。

Actual example I was using, to destructure a list and return a tuple of the first 2 items: 我正在使用的实际示例用于解构列表并返回前两个项目的元组:

(p: List[Int]): Tuple2[Int, Int] => { val x :: y :: rest = p; (x, y) }

fails, but this succeeds 失败,但这成功

(p: List[Int]) => { val x :: y :: rest = p; (x, y) }: Tuple2[Int, Int]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM