我正试图围绕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
感谢您的时间!
答案 0 :(得分:5)
我想那里的文档已经过时了。如果您查看the code,则不会返回IpLocation
,而是Option[IpLocation]
。
Option
是scala标准库中的一个类型,它包含两个构造函数:None
和Some(value)
。所以在值是可选的情况下使用它。
for
只是语法糖。 for (x <- xs) { println(x) }
已翻译为xs.foreach(x => println(x))
。因此,您基本上会调用foreach
on选项,如果getLocation
返回了值,则会执行您的打印行。
答案 1 :(得分:1)
ipGeo.getLocation(...)
会返回Option
类型,其中包含位置。
如果所提供的IP没有位置,它将返回None
,如果htere是一个位置,它将返回Some(location)
如果有值,那么如果有值,则会在Option
类型中获取值,如果没有任何值,则无法获取值。