How to use Java collections (collection classes) in Scala applications

You can use Java Collections in a Scala app by using this import statement:

import scala.collection.JavaConversions._

I just tested the following Scala application that gets a Java collection from the MongoDB Java driver, and I can confirm that this works:

import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import scala.collection.JavaConversions._

object TestDatabaseConnection {

 def main(args: Array[String]) {
  val m = new Mongo()
  
  // connect to the test database
  val db = m.getDB("test")
  // get a Java Set here
  val collections = db.getCollectionNames

  // use it like a Scala collection here
  for (s <- collections) {
    println(s)
  }

  // print all the DBObject's in the current collection
  val collection = db.getCollection("foo")
  val cursor = collection.find
  while (cursor.hasNext) {
    val dbObject = cursor.next
    println(dbObject)
  }
 }
}