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

Scala Multiline Anonymous Closure Mapping Over Array

我正在尝试使用多行匿名闭包映射数组,但遇到了问题。 例如

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

我收到以下警告:

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

这意味着 httpHostsArray[Unit] 而不是 Array[HttpHost]

我知道我可以将其拆分为两个映射,但是为了更好地理解 Scala,在多行闭包中执行此操作时我在这里做错了什么?

如评论中所述,您 return 在地图中的事实导致您无法获得预期的结果。 @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.

因此您收到此警告。

类似于您的有效代码是:

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")
})

话虽如此,我会写如下:

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