Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

compiler warnings - 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. E.g.

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].

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?

question from:https://stackoverflow.com/questions/65930388/scala-multiline-anonymous-closure-mapping-over-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned in the comments, the fact that you return within your map, cause you to not get your expected result. A quote from The Point of No Return that @LuisMiguelMejíaSuárez linked in the comments:

A return expression, when evaluated, abandons the current computation and returns to the caller of the method in which return appears.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...