How to throw Mongo BasicDBList into an immutable scala list

I have a BasicDBList that is stored in a database. Now I am reading the data and trying to convert the list to an immutable scala list, as shown:

val collection = mongoFactory.getCollection("tokens") val appId = MongoDBObject("appId" -> id) val appDBObject = collection.findOne(appId) val scope: List[String] = appDBObject.get("scope").asInstanceOf[List[String]] 

However, I get a class exception saying that it is not possible to distinguish BasicDBList from scala immutable list.

I have tried various combinations, such as conversion to map, etc. Nothing is working.

+7
source share
1 answer

Since MongoDB stores arrays in the same way as JavaScript, like an object with integer keys indicating their index --- BasicDBList is needed to represent the object coming from the wire. Thus, currently Casbah does not automatically represent it as a Scala list .... BasicDBList is a HashMap, not a list.

HOWEVER, inside Casbah does implicit conversions so you can treat BasicDBList as LinearSeq [AnyRef]; LinearSeq is slightly different from the type tree than List, but a more suitable type for various reasons. Unfortunately, you cannot use with implicit conversions.

Currently, I recommend that you get the item as a DBList, and then either enter an annotation in the form of LinearSeq, which will use implicit, or simply call toList (it will implicitly provide the toList method).

 scala> val l = MongoDBList("foo", "bar", "baz") l: com.mongodb.BasicDBList = [ "foo" , "bar" , "baz"] scala> val obj = MongoDBObject("list" -> l) obj: com.mongodb.casbah.commons.Imports.DBObject = { "list" : [ "foo" , "bar" , "baz"]} scala> obj.as[BasicDBList]("list") res8: com.mongodb.casbah.Imports.BasicDBList = [ "foo" , "bar" , "baz"] scala> obj.as[BasicDBList]("list").toList res9: List[AnyRef] = List(foo, bar, baz) 

The methods as[T]: T and getAs[T]: Option[T] preferable, by the way, for casting, since they have some kind of blende inside to do a type massage. The next release of Casbah will include code, so if you ask for Seq, List, etc., DBList as and getAs will automatically convert them to the type you requested.

+12
source

All Articles