1
votes

I am new to Scala. I am confused by this compilation error:

I create this HashMap and use it in a number of functions:

val valuesMap:mutable.Map[String,Int]=mutable.HashMap()

I have a function with this signature:

def saveToPjCsv(map:mutable.Map[Any,Any], fileName: String, outputDir: String): Unit =

I pass the HashMap to the function:

DataFrameUtils.saveToPjCsv(valuesMap,"categoryMap",".\\DataManipulation\\")

And get this compilation error:

error: overloaded method value saveToPjCsv with alternatives: [INFO]
(map: scala.collection.mutable.Map[Any,Any],fileName: String,outputDir: String)Unit [INFO] (df: org.apache.spark.sql.DataFrame,fileName: String,outputDir: String)Unit [INFO] cannot be applied to (scala.collection.mutable.Map[String,Int], String, String)

Why doesn't Map[Any,Any] accept Map[String,Int]?

1

1 Answers

1
votes

What would happened if the method accept your Map[String,Int] as a parameter and then it insert "MyKey" -> "My value"? you would have a Map[String, Int] in your calling method that in fact is storing String -> String data. That's why that code can't compile.

From the perspective of the compiler the reason why it is failing is because mutable.Map[Any, Any] is a different type from mutable.Map[String, Int] and there is no hierarchical relation between them. The reason why there is no relation is because you are using mutable collections where variance can not be used.

If you were using an immutable collection that defines the type parameters with covariance this would work:

def saveToPjCsv(map:List[(Any, Any)], fileName: String, outputDir: String): Unit ={}

saveToPjCsv(List[(String, Int)](), "", "")

To understand better what is variance check this out