1

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.

wipman
  • 581
  • 6
  • 22

1 Answers1

2
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)
             }
           }
Christian
  • 4,543
  • 1
  • 22
  • 31
  • `var res: MongoCursor = _` did not work because: `local variables must be initialized`. So I used `null` and it worked. I will try what you advise once it works properly. Great thanks. – wipman Sep 24 '15 at 14:36