Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何选择从映射函数返回值_Scala - Fatal编程技术网

Scala 如何选择从映射函数返回值

Scala 如何选择从映射函数返回值,scala,Scala,map集合上的函数需要为每次迭代返回一些值。但我试图找到一种方法,不是为每次迭代返回值,而是只为匹配某个谓词的初始值返回值 我想要的是这样的: (1 to 10).map { x => val res: Option[Int] = service.getById(x) if (res.isDefined) Pair(x, res.get )// no else part } 我认为类似于.collect函数的功能可以做到这一点,但似乎使用collect函数,我需要在保护块中

map
集合上的函数需要为每次迭代返回一些值。但我试图找到一种方法,不是为每次迭代返回值,而是只为匹配某个谓词的初始值返回值

我想要的是这样的:

(1 to 10).map { x =>
   val res: Option[Int] = service.getById(x)
   if (res.isDefined) Pair(x, res.get )// no else part

}

我认为类似于
.collect
函数的功能可以做到这一点,但似乎使用
collect
函数,我需要在保护块中编写许多代码(
case x,如果{…//这里的代码太多}

如果返回
选项
,则可以
平面映射
它并仅获取当前的值(也就是说,它们不是
None


正如您所建议的,组合
map
filter
的另一种方法是使用
collect
和部分应用的函数。下面是一个简化示例:

(1 to 10).collect{ case x if x > 5 => x*2 }
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(12, 14, 16, 18, 20)

您可以使用collect函数完全执行您想要的操作。您的示例如下所示:

(1 to 10) map (x => (x, service.getById(x))) collect {  
  case (x, Some(res)) => Pair(x, res)
}

获取第一个元素:

(1 to 10).flatMap { x =>
   val res: Option[Int] = service.getById(x)
   res.map{y => Pair(x, y) }
}.head

用a来理解,像这样

for ( x <- 1 to 10; res <- service.getById(x) ) yield Pair(x, res.get)

for(x)我也喜欢这个解决方案。我想知道我们是否可以比较一下性能,看看使用部分应用的函数与flatmap解决方案是否有什么不同……我在这里遗漏了一些东西。
x
从何处检索?当您在
collect()中时,它是否已经丢失了
?很好的观点@jwvh。不再有x了,我们需要保留第一个map的结果(返回一个元组或什么)。因为OP听起来像是在搜索最小的代码,我会重写为
(1到10)。flatMap(x=>service.getById(x)。map(Pair(x,)))
for ( x <- 1 to 10; res <- service.getById(x) ) yield Pair(x, res.get)