user1052610
user1052610

Reputation: 4719

Passing parameters to an object on construction

An object needs to hold a globally available cache. In order to initialize the cache, the object needs to be passed a variable obtained from a third party framework running within the application.

As objects do not take constructor parameters, how is it possible to pass the variable from the framework to the object so that it is available during object construction?

A workaround would be to have an init method on the object (which accepts the third party framework variable), and add some scaffolding code. However, is there a better way?

Upvotes: 0

Views: 113

Answers (2)

Som Bhattacharyya
Som Bhattacharyya

Reputation: 4112

Hmm so i would not recommend writing a cache yourself. There are libraries that do the job better. There is this Scala project called Mango that wraps the excellent Java based Guava library that gives caching abilities.

You could write code like this(From the documentation) ,

import java.util.concurrent.TimeUnit
import org.feijoas.mango.common.cache._

// the function to cache
val expensiveFnc = (str: String) => str.length  //> expensiveFnc  : String => Int 

// create a cache with a maximum size of 100 and 
// exiration time of 10 minutes
val cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(expensiveFnc)              //> cache  : LoadingCache[String,Int]

cache("MyString")  //

Also there is a simple library called ScalaCache that is excellent at this. Check it here This works only with Scala 2.11 onwards because the use of macros.

Upvotes: 1

Chris Martin
Chris Martin

Reputation: 30736

Generally you don't put mutable state on an object. But if you really need to, you could put a var field on it.

object TheObject {
    var globalMutableState: Option[TheStateType] = None
}

Whatever needs to set that state can do so with an assignment.

TheObject.globalMutableState = Some(???)

And whatever needs to refer to it can do so directly.

TheObject.globalMutableState.get

Upvotes: 2

Related Questions