加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

为什么使用元组的Scala表达式无法编译?

发布时间:2020-12-16 19:21:09 所属栏目:安全 来源:网络整理
导读:使用 Scala 2.8.1,编译: 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:
使用 Scala 2.8.1,编译:

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)]
println(for ((i,j) <- e.right) yield i + j)

根据Scala中的Programming,for表达式应该等同于map / case表达式,但只有后者才能编译.我做错了什么,我应该怎么做?

解决方法

实际上,这并不是正在发生的翻译.您可以参考 this answer获得更完整的指南,但即使在那里也没有明确提到这种情况.

通过模式匹配进行理解可以过滤不匹配的情况.例如,

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

将返回List((1,2)):List [(Any,Any)],因为首先调用withFilter.现在,要么似乎没有withFilter,所以它将使用过滤器,这里是理解的实际翻译:

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

这给出了完全相同的错误.问题是e.right返回RightProjection,但在RightProjection [A,B]上过滤返回Option [[Nothing,B]].

原因是没有“空”Either(或RightProjection)这样的东西,所以需要将其结果封装在Option上.

说了这么多,看看for-comprehension水平真是令人惊讶.我认为正确的做法是过滤器返回某种过滤后的投影.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读