0

我正在尝试围绕 Scala 进行研究,到目前为止,我发现它非常具有挑战性。我找到了这个库(https://github.com/snowplow/scala-maxmind-geoip),我过去使用 Python 来查找基于 IP 地址的国家/地区等内容。

所以这个例子很简单

import com.snowplowanalytics.maxmind.geoip.IpGeo

val ipGeo = IpGeo(dbFile = "/opt/maxmind/GeoLiteCity.dat", memCache = false, lruCache = 20000)

for (loc <- ipGeo.getLocation("213.52.50.8")) {
  println(loc.countryCode)   // => "NO"
  println(loc.countryName)   // => "Norway" 
}

并且文档显示

getLocation(ip) 方法返回一个 IpLocation 案例类

那么,如果它是一个案例类,为什么这不起作用呢?

val loc = ipGeo.getLocation("213.52.50.8")
println(loc.countryCode)

毕竟我能做到

case class Team(team: String, country: String)
val u = Team("Barcelon", "Spain")
scala> u.country
res5: String = Spain

感谢您的时间!

4

2 回答 2

5

我猜那里的文档已经过时了。如果您查看代码,它不会返回 aIpLocation而是返回Option[IpLocation].

Option是 scala 标准库中的一个类型,它有两个构造函数:NoneSome(value). 所以它用于值是可选的。

for在 scala 中只是语法糖。for (x <- xs) { println(x) }被翻译成xs.foreach(x => println(x)). 因此,您基本上调用foreachon 选项,如果getLocation.

于 2014-06-13T11:43:43.423 回答
1

ipGeo.getLocation(...)返回具有Option内部位置的类型。

也许如果提供的 IP 没有位置,它将返回None,如果 htere 是一个位置,它将返回Some(location)

使用 for 理解,如果有值,您将获得Option类型内的值,如果没有任何值,则什么都没有。

于 2014-06-13T11:42:54.107 回答