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

scala – 为什么与tuple类型的提取器一起使用的for-comprehensio

发布时间:2020-12-16 19:16:26 所属栏目:安全 来源:网络整理
导读:给出以下代码snippelt: import scala.util.Trydef foo(x:Int) : (Int,String) = { (x+1,x.toString)}def main(args: Array[String]) : Unit = { val r1: Try[(Int,String)] = for { v - Try { foo(3) } } yield v val r2: Try[(Int,String)] = for { (i,s)
给出以下代码snippelt:

import scala.util.Try

def foo(x:Int) : (Int,String) = {
  (x+1,x.toString)
}

def main(args: Array[String]) : Unit = {
  val r1: Try[(Int,String)] = for {
    v <- Try { foo(3) }
  } yield v

  val r2: Try[(Int,String)] = for {
    (i,s)  <- Try { foo(3) } // compile warning refers to this line
  } yield (i,s)
}

1.为什么编译上面的代码会抛出以下警告?

`withFilter' method does not yet exist on scala.util.Try[(Int,String)],using `filter' method instead
[warn]       (i,s)  <- Try { foo(3) }
[warn]                      ^
[warn] one warning found

2.为什么在提取元组时使用withFilter?

更新

> Scala 2.10.5发出警告
> Scala 2.11.7不会发出警告

独立于警告信息,我很想知道是否使用了withFilter? (见问题2)

解决方法

似乎Try.withFilter仅在2.11中添加(见 Try 2.10.6和 Try 2.11.0)

forFilter用于代替过滤器,因为它很懒,你可以在this question中阅读更全面的比较.

你理解的第二个类似于:

Try(foo(3)).withFilter {
  case (i,s) => true
  case _      => false
} map(identity)

因为在Scala 2.10.5中Try.withFilter不存在,所以它回退到使用filter(创建一个新的Try).

编辑:为什么你需要withFilter在你的情况下并不那么明显,因为你实际上并没有使用(i,s)模式匹配进行过滤.

如果您在下面编写了for comprehension,则更清楚的是,您可以在为了便于理解的左侧添加模式匹配时进行过滤.

for {
  (i,"3") <- Try(foo(3))
} yield i

这类似于:

Try(foo(3)) withFilter {
  case (i,"3") => true
  case _        => false
} map { case (i,"3") => i }

正如您所看到的,withFilter不仅可以在添加if guard时使用,还可以在模式匹配时使用.

(编辑:李大同)

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

    推荐文章
      热点阅读