问题描述
我正在尝试使用多行匿名闭包映射数组,但遇到了问题。 例如
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
这意味着 httpHosts
是 Array[Unit]
而不是 Array[HttpHost]
。
我知道我可以将其拆分为两个映射,但是为了更好地理解 Scala,在多行闭包中执行此操作时我在这里做错了什么?
解决方法
如评论中所述,您在地图内返回这一事实会导致您无法获得预期结果。 @LuisMiguelMejíaSuárez 在评论中链接的来自 The Point of No Return 的引用:
返回表达式在求值时放弃当前计算并返回到出现 return 的方法的调用者。
因此您会收到此警告。
与您的工作代码类似的是:
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")
}