Scala Code:-
import scala.io.Source
object Stocks1 {
val filename = "stocks.csv"
def main(args: Array[String]): Unit = {
readStocks(filename)
}
def readStocks(fn: String): Map[String, Float] = {
//def readStocks(fn: String): Unit = {
def percentChange(observed: Float, expected: Float): Float = {
if (observed == 0 && expected == 0)
0.0f
else
((observed - expected) * 100) / expected
}
for (line <- Source.fromFile(fn).getLines()) {
val list1 = line.split(",").map(_.trim).toList
//Assigning Map to a val so in order to return Map(String,Float)
val stock_map=Map(list1(2)->percentChange(list1(5).toFloat,list1(6).toFloat))
stock_map
}
}
我必须返回Map[String, Float]
,但我不知道该怎么做。我对scala很新。我尝试将它分配给stock_map
Map(list1(2)->percentChange(list1(5).toFloat,list1(6).toFloat))
但我收到的错误为Type MIsmatch. Expected "Map[String, Float]" found "Unit"
。
答案 0 :(得分:1)
请尝试以下操作。
(for {
line <- io.Source.fromFile(fn).getLines()
list1 = line.split(",").map(_.trim).toList
} yield list1(2)->percentChange(list1(5).toFloat,list1(6).toFloat)
).toMap
Scala for
理解不像for()
循环在其他语言中那样工作。初学者可能会发现,在他们对自己的工作方式有一个公平的理解之前,避免它们是有利的。
考虑到这一点,这就是for
理解所做的事情,这可能会更容易理解。
io.Source.fromFile(fn).getLines().map{ line =>
val list1 = line.split(",").map(_.trim).toList
list1(2) -> percentChange(list1(5).toFloat, list1(6).toFloat)
}.toMap