1
votes

Is there any way to create mutable map in scala by using variables? I am reading a csv file with source.fromFile("abc.csv").getlines. I want 1st 2 columns of this file to be the key and rest as values. I want to do the same with 2nd file so I can compare these 2 files based on the key and get the difference. eg: file abc.csv is as below: Company,Empid,Name 1,10,Abc 1,11,PQR 2,10,XYZ

I want o/p as Map(110->Abc,111->PQR, 210->XYZ)

I tried to achieve it by:

var keymap = collection.mutable.Map[Int,String]()
val content = Source.fromFile("abc.csv").getLines;
val data = content.drop(1); //to remove header
for (line <-data){   
    val x = line.substring(0,1).toInt;
    val y = line.substring(2,4).toInt;
    var key = (x*100) + y;
    var value = line.substring(9);
    var keymap += (key,value);
}

But it gives error as - :60: error: type mismatch; found : Int required: (Int, String) keymap += (key,value) ^

Can someone please suggest what I am doing wrong or is there a better way to do this? Thanks!

1
There is no need of mutable map to do socchantep

1 Answers

0
votes

If keymap is mutable, why are you taking it as var, take it as val.Try this.

scala> val tasks = mutable.Map[Int,String]()
tasks: scala.collection.mutable.Map[Int,String] = Map()
scala> tasks += (1,"Book a movie ticket")
<console>:14: error: type mismatch;
 found   : Int(1)
 required: (Int, String)
       tasks += (1,"Book a movie ticket")
scala> tasks += (1 -> "Book a movie ticket")
res13: tasks.type = Map(2 -> " movie ticket", 1 -> Book a movie ticket)

So, you have to change this

keymap += (key-> value)