0
votes

As the (non-functioning) code below shows, I want to take any hashmap and convert to spreadsheet format.

  def printHashMapToCsv[T](m:Map[T,T],name:String, path:String): Unit =
  {
    Spreadsheet.initCsvSpreadsheet(name,path)
    m.foreach
    {
      e=> Spreadsheet.addCell(IDGenerator.getInstance().nextID(),e._1.toString,e._2.toString)
    }
    Spreadsheet.printCsvFinal()
  }

The code above compiles, but I get a compilation method when I try to call the method using the code below:

def mapOut(): Unit =
  {
    try{

      val m:mutable.HashMap[Int,String]=new mutable.HashMap[Int,String]()
      m.put(1,"sssss")
      m.put(2,"ghfd")
      m.put(3,"dfsa")
      m.put(4,"fhjgsdf")
      printHashMapToCsv(m,"mapout",s"${new File(".").getAbsolutePath}${File.separator}unitTestOutput")

    }

Compilation error:

error: type mismatch; [INFO] found : scala.collection.mutable.HashMap[Int,String] [INFO] required: Map[?,?]

Any advice would be appreciated

1
Your printHashMapToCsv[T] method expects a Map[T, T] (i.e. both key & value of the same type) whereas you're feeding it a mutable.HashMap[Int, String].Leo C
got it, that explains the errorJake

1 Answers

1
votes

It seems you pass only one type parameter T to the printHashMapToCsv method, and make it expects a Map[T, T] :

def printHashMapToCsv[T](m:Map[T,T], name:String, path:String)

However, you give it a Map[Int, String], so two different types :

val m:mutable.HashMap[Int,String]=new mutable.HashMap[Int,String]()
printHashMapToCsv(m,"mapout",s"${new File(".").getAbsolutePath}${File.separator}unitTestOutput")

I you want to pass 2 types to it, this method definition should do the trick :

def printHashMapToCsv[T, U](m:Map[T, U], name:String, path:String)

However, if you know that one of the type you pass will always be the same (The Int for example), you should keep only one type parameter and explicitly require it, like this :

def printHashMapToCsv[T](m:Map[Int, T], name:String, path:String)

Hope this help !