Frage

I'm trying to convert below Java code to Scala:

Map<String, List<String>> allEntriesMap = getEntries();
for (Map.Entry<String, List<String>> allEntriesMapEntry : allEntriesMap
        .entrySet()) {
}

Here is the current Scala version of above Java code:

var allEntriesMap : Map[String, List[String]] = getEntries();
for (allEntriesMap.entrySet[String, List[String]] allEntriesMapEntry :
        allEntriesMap.entrySet()) {
}

I'm receiving this error for line

for (allEntriesMap.entrySet[String, List[String]] allEntriesMapEntry : 

illegal start of simple pattern

How can above code be finished so that it performs same Java functionality but written in Scala?

War es hilfreich?

Lösung

The problem is that you use incorrect syntax. This

for (allEntriesMap.entrySet[String, List[String]] allEntriesMapEntry : allEntriesMap.entrySet()) {

    }

Should be written as:

for (entry: Map.Entry[String, List[String]] <- allEntriesMap.entrySet()) {

}

or simply

for (entry <- allEntriesMap.entrySet) {

}

Moreover, if you're using java collections type you have to import scala.collections.JavaConversions._ into scope (that will implicitly convert java collections into scala ones, so you may use all set of operations on them).

Andere Tipps

This is a syntax error, because the for loop uses different syntax in Scala than it does in Java. (It doesn't use the colon for anything -- it uses the left-pointing arrow instead.)

Your code should look like the following:

import scala.collection.JavaConversions._

for ((key, value) <- getEntries()) {
  // ...
}

You can apply some function for every element of the map by using foreach(), map() etc. functions. So you will deal with tuple in Scala as with Map.Entry object in Java.

E.g. you can use following code to flush all values in your map.

var allEntriesMap : Map[String, List[String]] = getEntries()

allEntriesMap.foreach((arg: (String, List[String])) => {arg._2 = List.empty[String]})
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top