4

How can the following be converted to scala? If I live it as it is, I'm getting a big type mismatch expected

.entrySet().forEach(entry -> {..})

I tried specifying entry to java.util.Map.Entry, or changing to scala foreach, doesn't work.

Let me know if you need any more info/code, and I'll create some dummy example since I'm not allowed to post the exact code.

KKO
  • 1,913
  • 3
  • 27
  • 35
  • I'd say you want an implicit conversion. http://stackoverflow.com/questions/7481204/smooth-way-of-using-functiona-r-java-interface-from-scala – Marko Topolnik Feb 23 '15 at 09:17
  • `for(entry <- entrySet){...}` – Mariusz Nosiński Feb 23 '15 at 09:20
  • If it's a `java.util.Map` then you either want the implicit conversion for the function as suggested by @MarkoTopolnik, or to convert it to a scala map using `.asScala` with `import scala.util.JavaConverters._` at the top. Or you can explicitly instantiate a `new Function(){}` the way you would in Java. If it's a `scala.collection.Map` then the `for(entry ← ...)` approach is what you want. – lmm Feb 23 '15 at 09:29

2 Answers2

3

check this

Iterating over Java collections in Scala

for each in scala

for(entry<-entrySet){
//
}

or

entrySet.foreach{entry=>
//
}

or

.entrySet.map{entry => 
//
}
Community
  • 1
  • 1
Govind Singh
  • 15,282
  • 14
  • 72
  • 106
1

Just

import scala.collection.JavaConversions._

for an implicit conversion to scala collections.

gun
  • 1,046
  • 11
  • 22
  • 3
    Please don't suggest using implicit conversions. [Decorators](http://www.scala-lang.org/api/current/index.html#scala.collection.convert.DecorateAsScala) are the way to go: `import scala.collection.convert.decorateAsScala._; javaCollection.asScala.foreach(x => doSomething(x))`. – Vladimir Matveev Feb 23 '15 at 19:27
  • 2
    Good point! It's explained in this post: http://stackoverflow.com/questions/8301947/what-is-the-difference-between-javaconverters-and-javaconversions-in-scala – gun Feb 24 '15 at 08:39
  • Both `scala.collection.JavaConversions._` and `scala.collection.convert.decorateAsScala` are deprecated. The current way is (until it is also deprecated in some future) `import scala.collection.JavaConverters._; javaCollection.asScala.foreach(x => doSomething(x))` – yerlilbilgin Nov 27 '18 at 13:04