Scala:帮助我理解此代码中的理解和案例类

时间:2014-06-13 11:24:45

标签: scala case-class for-comprehension

我正试图围绕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

感谢您的时间!

2 个答案:

答案 0 :(得分:5)

我想那里的文档已经过时了。如果您查看the code,则不会返回IpLocation,而是Option[IpLocation]

Option是scala标准库中的一个类型,它包含两个构造函数:NoneSome(value)。所以在值是可选的情况下使用它。

scala中的

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类型中获取值,如果没有任何值,则无法获取值。