[英]why can't I have a for loop inside an anonymous function in scala?
when I try to run the following code: 当我尝试运行以下代码时:
val anonFunc = (x: Pos): List[Pos] => {for(i <- 1 to 10){ println(i)}
I get the following error: 我收到以下错误:
illegal start of declaration
and I have no idea why. 我不知道为什么 This code is used inside a function
此代码在函数内部使用
(1) There two ways to ensure correct return type of anonymous function that I know: (1)我知道有两种方法可以确保匿名函数的正确返回类型:
val f = (x: Int) => { x + 1 }: Double
val f: Int => Double = x => x + 1
(2) Your for
comprehension will return Unit
as it's written, not List[Pos]
. (2)您
for
理解力将按书面形式返回Unit
,而不是List[Pos]
。 To return something real you need to use yield
: 要返回真实的东西,您需要使用
yield
:
val anonFunc = (x: Pos) => { for(i <- 1 to 10) yield(x) }: List[Pos]
but as you do this you will notice that compiler doesn't like List
as a return type because what for
returns is IndexedSeq
, not List
. 但是,你这样做,你会发现,编译器不喜欢
List
作为返回类型,因为什么for
回报是IndexedSeq
,而不是List
。 So you need to convert it explicitly: 因此,您需要对其进行显式转换:
val anonFunc = (x: Pos) => { for(i <- 1 to 10) yield(x) }.toList: List[Pos]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.