Search code examples
javamongodbscalascala-2.10scala-2.11

how to pass different values to a variable in a scala object


I want to create different collection in mongodb for that i have a scala object class here is my code

object Factory {

val connectionMongo = MongoConnection(SERVER)
val collectionMongo = connectionMongo(DATABASE)("collectionA")

}

i want to add different collection names for that i am doing it like this object class here is my code

    object Factory {

    var COLLECTIONName:String=""
    def setCollectionName(name:String)
    {
      COLLECTIONName=name
    }
    val connectionMongo = MongoConnection(SERVER)
    val collectionMongo = connectionMongo(DATABASE)(COLLECTIONName)

    }

class testA {

//getting collection object 
Factory.setCollectionName("collectionA")
collectionMongo.find()//fetching the record of collectionA

}

class testB {

//getting collection object 
Factory.setCollectionName("collectionB")
collectionMongo.find()//fetching the record of collectionB
}

but this code is not working as desired it always gets COLLECTIONName value to empty string "" please guide me where i am doing wrong ,please help


Solution

  • This is a typical factory pattern, you can change your collectionMongo from a val into a function like this

    object Factory {
        val SERVER = "<some server>"
        val DATABASE = "<some database>"
        val connectionMongo = MongoConnection(SERVER)(DATABASE)
        def getCollection(name: String) = connectionMongo(name)
    }
    

    Usage

    class testA {
        val collectionA = Factory.getCollection(nameA)
    }
    
    class testB {
        val collectionB = Factory.getCollection(nameB)
    }