我有一个国家/地区的csv文件和一个CountryData案例类
来自档案的示例数据:
丹麦,欧洲,1.23,7.89
澳大利亚,澳大利亚,8.88,9.99
巴西,南美洲,7.77,3.33
case class CountryData(country: String, region: String, population: Double, economy: Double)
我可以在文件中读取并拆分等以获取
(列表(丹麦,欧洲,1.23,7.89) (列表(澳大利亚,澳大利亚,8.88,9.99) (名单(巴西,南美洲,7.77,3.33)
我现在如何为每个列表项填充CountryData案例类? 我试过了:
for (line <- Source.getLines.drop(1)) {
val splitInput = line.split(",", -1).map(_.trim).toList
val country = splitInput(0)
val region = splitInput(1)
val population = splitInput(2)
val economy = splitInput(3)
val dataList: List[CountryData]=List(CountryData(country,region,population,economy))
但这不起作用,因为它没有阅读val,它认为它是一个字符串&#39; country&#39;或者&#39;地区&#39;。
答案 0 :(得分:0)
目前尚不清楚您的问题究竟在哪里。是关于Double
vs String
还是约List
在圈内。仍然这样的事情可能会起作用
case class CountryData(country: String, region: String, population: Double, economy: Double)
object CountryDataMain extends App {
val src = "\nDenmark, Europe, 1.23, 7.89\nAustralia, Australia, 8.88, 9.99\nBrazil, South America, 7.77,3.33"
val list = Source.fromString(src).getLines.drop(1).map(line => {
val splitInput = line.split(",", -1).map(_.trim).toList
val country = splitInput(0)
val region = splitInput(1)
val population = splitInput(2)
val economy = splitInput(3)
CountryData(country, region, population.toDouble, economy.toDouble)
}).toList
println(list)
}
答案 1 :(得分:0)
我会使用scala case匹配:即
int - int