简体   繁体   English

Scala 数组上的多行匿名闭包映射

[英]Scala Multiline Anonymous Closure Mapping Over Array

I'm trying to map over an array using a multiline anonymous closure and I'm having trouble.我正在尝试使用多行匿名闭包在数组上 map 并且遇到了麻烦。 Eg例如

val httpHosts = stringHosts.map(host => {
  val hostAndPort = host.split(":")
  return new HttpHost(hostAndPort(0), hostAndPort(1).toInt, "http")
})

I'm receiving the following warning:我收到以下警告:

enclosing method executePlan has result type Unit: return value of type org.apache.http.HttpHost discarded

Which implies that httpHosts is an Array[Unit] and not an Array[HttpHost] .这意味着httpHostsArray[Unit]而不是Array[HttpHost]

I understand that I can split this into two maps, but for the sake of understanding Scala better, what am I doing wrong here when doing this in a multiline closure?我知道我可以将其拆分为两个地图,但为了更好地理解 Scala,在多行闭包中执行此操作时我在这里做错了什么?

As mentioned in the comments, the fact that you return within your map, cause you to not get your expected result.如评论中所述,您在 map 内返回的事实导致您无法获得预期的结果。 A quote from The Point of No Return that @LuisMiguelMejíaSuárez linked in the comments: @LuisMiguelMejíaSuárez 在评论中链接的 The Point of No Return的引述:

A return expression, when evaluated, abandons the current computation and returns to the caller of the method in which return appears.返回表达式在计算时会放弃当前计算并返回到出现 return 的方法的调用者。

Therefore you get this warning.因此,您会收到此警告。

Similar to your code that works is:与您的有效代码类似的是:

case class HttpHost(host: String, port: Int, protocol: String)
val httpHosts = stringHosts.map(host => {
  val hostAndPort = host.split(":")
  HttpHost(hostAndPort(0), hostAndPort(1).toInt, "http")
})

Having said that, I'd write it the following:话虽如此,我会写如下:

val httpHosts1 = stringHosts.map(_.split(":")).collect {
  case Array(host, port) if port.toIntOption.isDefined =>
    HttpHost(host, port.toInt, "http")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM