Issaq
Issaq

Reputation: 41

Scala - Return Map from a function in scala

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
    }
  }

I have to return Map[String, Float] but i don't know how to do it. I am pretty new to scala. I tried assigning it to stock_map to Map(list1(2)->percentChange(list1(5).toFloat,list1(6).toFloat)) but I am getting error as Type MIsmatch. Expected "Map[String, Float]" found "Unit".

Upvotes: 1

Views: 920

Answers (1)

jwvh
jwvh

Reputation: 51271

Try the following.

(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 comprehensions don't work the way for() loops do in other languages. Beginners might find it advantageous to avoid them until they've achieved a fair understanding of how they work.

With that in mind, this is what the for comprehension is doing, which might be a little easier to understand.

io.Source.fromFile(fn).getLines().map{ line =>
  val list1 = line.split(",").map(_.trim).toList
  list1(2) -> percentChange(list1(5).toFloat, list1(6).toFloat)
}.toMap

Upvotes: 1

Related Questions