为什么使用元组的Scala表达表达式无法编译? [英] Why does this Scala for expression using tuples fail to compile?

查看:108
本文介绍了为什么使用元组的Scala表达表达式无法编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Scala 2.8.1进行编译:

With Scala 2.8.1, compiling this:

val t = (40, 2)

println(for ((i, j) <- List(t)) yield i + j)

val e: Either[String, (Int, Int)] = Right(t)
println(e.right.map {
  case (i, j) => i + j
})
println(for ((i, j) <- e.right) yield i + j)

给出此:

test.scala:9: error: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: Either[Nothing,(Int, Int)]
println(for ((i, j) <- e.right) yield i + j)

根据在Scala中编程,for表达式应等效映射/案例表达式,但只有后者可以编译。我在做什么错了,我应该怎么做?

According to Programming in Scala, the for expression should be equivalent to the map/case expression, but only the latter compiles. What am I doing wrong, and how should I do this?

推荐答案

实际上,那不是相当正在发生的翻译。您可以参考此答案,以获得更完整的指南,但这

Actually, that is not quite the translation that is happening. You may refer to this answer for a more complete guide, but this case is not explicitly mentioned even there.

发生的情况是,具有模式匹配的for理解会过滤掉不匹配的情况。例如,

What happens is that a for comprehension with pattern matching filters the non-matching case. For example,

for((i, j) <- List((1, 2), 3)) yield (i, j)

将返回 List((1,2)): List [(Any,Any)] ,因为首先调用 withFilter 。现在,任何一个似乎都没有 withFilter ,因此它将使用 filter ,这是理解的实际翻译:

will return List((1, 2)): List[(Any, Any)], as withFilter is called first. Now, Either doesn't seem to have withFilter, so it will use filter, and here's the actual translation of that for comprehension:

e.right.filter { case (i, j) => true; case _ => false }.map { case (i, j) => i + j }

给出完全相同的错误。问题是 e.right 返回 RightProjection ,但是 filter RightProjection [A,B] 上的c>返回 Option [Either [Nothing,B]]

Which gives exactly the same error. The problem is that e.right returns a RightProjection, but filter on RightProjection[A, B] returns Option[Either[Nothing, B]].

其原因是没有空 或者(或 RightProjection ),因此它需要将结果封装在 Option 中。

The reason for that is that there is no such thing as an "empty" Either (or RightProjection), so it needs to encapsulate its result on an Option.

所有这一切,从理解水平来看确实令人惊讶。我认为正确的做法是让 filter 返回某种经过过滤的投影。

Having said all that, it is truly surprising when looked at the for-comprehension level. I think the right thing would be for filter to return some kind of filtered projection instead.

这篇关于为什么使用元组的Scala表达表达式无法编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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