I need a var
(res
in the following) to accept the answer of a find()
, i.e. MongoCursor
, because I have to have access to my var inside if
-conditions (see below).
Here is what I am doing:
var query = new MongoDBObject()
val res = ""
if ("condition_1" == field_1))
{
query += "field" -> "t"
if ("condition_2" == "field_2"))
{
res = collection.find(q).sort("basic_field" -> 1)
}
else if ("condition_2" == "field_2"))
{
res = collection.find(q).sort("important_field" -> -1).limit(101)
}
}
//Perform some operations on res
How can I initialize my res
to accept a MongoCursor
?
var res = MongoCursor
and var res = DBCursor
do not function.
var res: MongoCursor = _
This assigns the default value to res (probably null).
But you should avoid using var wherever possible. Because in scala if can return a result it's possible to directly assign the result to res, e.g.:
val res = if ("condition_1" == field_1)) {
query += "field" -> "t"
if ("condition_2" == "field_2")) {
collection.find(q).sort("basic_field" -> 1)
} else if ("condition_2" == "field_2")) {
collection.find(q).sort("important_field" -> -1).limit(101)
}
}