1
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".

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot!! your solution worked!!. Yes this is my first scala program didn't have thorough understanding of the for loop comprehension.
One more thing i am trying to append values to the list as it's immutable i can't do that. And i can't use "var" at all. So i have used ListBuffer with "val" reference but i am still having issues. Any help will be appreciated ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.