我是Scala的新手所以请耐心等待.我对以下行为感到困惑:
val l = List(Option(1))
for (i <- l; x <- i) yield x //Example 1: gives me List(1)
for(x <- Option(1)) yield x //Example 2: gives me Some(1)
Run Code Online (Sandbox Code Playgroud)
为什么理解的第二个1不是给我的?因为直观地说,这对我来说看起来更加一致,因为第一个示例中的第二个用于理解x <- i看起来应该与第二个示例的行为完全相同,因为第二个示例基本上已经从列表中提取了选项以开始.
简单地说,为了理解包装第一次使用的类型.
for (x <- Option(1)) yield x // Returns Option
for (x <- List(1)) yield x // Returns List
for (x <- Array(1)) yield x // Returns Array
Run Code Online (Sandbox Code Playgroud)
这个:
for (i <- List(Some(1)); x <- i) yield x
Run Code Online (Sandbox Code Playgroud)
Desugares到这个:
List(Some(1)).flatMap { case i => i.map { case x => x } }
Run Code Online (Sandbox Code Playgroud)
flatMap的List回报List[T],这就是为什么它的行为像