Today I was converting a servlet from a Java implementation to a Scala implementation. I needed to print out the parameters (getParameterMap) and headers (getHeaderNames). These are implemented as java.util.Map collections with the following definition.
java.util.Map<java.lang.String,java.lang.String[]>
Using the implicit conversion of Scala did not work as straight forward as I thought. I started of with the following code.
def makeKeyValuePair(key: String, values: Array[String], length: Int) : String = { if (length == 0) s"$key=$values" else s", $key=$values" } def parameters(request: HttpServletRequest) : String = { var s = "" for ((k, v) <- request.getParameterMap()) s += makeKeyValuePair(k, v, s.length()) }
That would give me a not very helpful error message (at least I think the error message is rather cryptic)
type mismatch; found : ?0 where type ?0 required: String
It took me a while, but I finally figured out I needed to explicitly declare the k and v variable types. So this is the final code.
def makeKeyValuePair(key: String, values: Array[String], length: Int) : String { if (length == 0) s"$key=$values" else s", $key=$values" } def parameters(request: HttpServletRequest) : String = { var s = "" for ((k: String, v: Array[String]) <- request.getParameterMap()) s += makeKeyValuePair(k, v, s.length()) }
I hope this helps someone else from having to solve the explicit conversion problem.