在 for-comprehension 中使用 List 组合选项会根据顺序给出类型不匹配 [英] Composing Option with List in for-comprehension gives type mismatch depending on order

查看:23
本文介绍了在 for-comprehension 中使用 List 组合选项会根据顺序给出类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这种构造会导致 Scala 中出现类型不匹配错误?

Why does this construction cause a Type Mismatch error in Scala?

for (first <- Some(1); second <- List(1,2,3)) yield (first,second)

<console>:6: error: type mismatch;
 found   : List[(Int, Int)]
 required: Option[?]
       for (first <- Some(1); second <- List(1,2,3)) yield (first,second)

如果我用 List 切换 Some ,它编译得很好:

If I switch the Some with the List it compiles fine:

for (first <- List(1,2,3); second <- Some(1)) yield (first,second)
res41: List[(Int, Int)] = List((1,1), (2,1), (3,1))

这也很好用:

for (first <- Some(1); second <- Some(2)) yield (first,second)

推荐答案

For comprehensions 转换为对 mapflatMap 方法的调用.例如这个:

For comprehensions are converted into calls to the map or flatMap method. For example this one:

for(x <- List(1) ; y <- List(1,2,3)) yield (x,y)

变成:

List(1).flatMap(x => List(1,2,3).map(y => (x,y)))

因此,第一个循环值(在本例中为 List(1))将接收 flatMap 方法调用.由于List 上的flatMap 返回另一个List,for comprehension 的结果当然是一个List.(这对我来说是新的:因为理解并不总是导致流,甚至不一定在 Seq 中.)

Therefore, the first loop value (in this case, List(1)) will receive the flatMap method call. Since flatMap on a List returns another List, the result of the for comprehension will of course be a List. (This was new to me: For comprehensions don't always result in streams, not even necessarily in Seqs.)

现在,看看flatMap是如何在Option中声明的:

Now, take a look at how flatMap is declared in Option:

def flatMap [B] (f: (A) ⇒ Option[B]) : Option[B]

记住这一点.让我们看看理解的错误(带有 Some(1) 的错误)如何转换为一系列 map 调用:

Keep this in mind. Let's see how the erroneous for comprehension (the one with Some(1)) gets converted to a sequence of map calls:

Some(1).flatMap(x => List(1,2,3).map(y => (x, y)))

现在,很容易看出 flatMap 调用的参数返回的是 List,而不是 Option,如需要.

Now, it's easy to see that the parameter of the flatMap call is something that returns a List, but not an Option, as required.

为了解决这个问题,您可以执行以下操作:

In order to fix the thing, you can do the following:

for(x <- Some(1).toSeq ; y <- List(1,2,3)) yield (x, y)

编译就好了.值得注意的是,Option 不是 Seq 的子类型,正如人们通常认为的那样.

That compiles just fine. It is worth noting that Option is not a subtype of Seq, as is often assumed.

这篇关于在 for-comprehension 中使用 List 组合选项会根据顺序给出类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆