paul paul - 2 months ago 7
Scala Question

Call method in constructor

I have a Controller with a constructor where I´m injecting a cache, but also I would like to invoke a method in the constructor when the instance is created. I know we can create some auxiliary constructors with

def this(foo:Foo){}


But in my case because is play framework the one that instance my bootstrap is a little bit more complex.

Here my code

class SteamController @Inject()(cache: CacheApi) extends BaseController {

private val GAME_IDS_LIST_API: String = "api.steampowered.com/ISteamApps/GetAppList/v2"

private val GAME_API: String = "store.steampowered.com/api/appdetails?appids="

private val GAME_KEY: String = "games"

def games = Action { implicit request =>
var fromRequest = request.getQueryString("from")
if (fromRequest.isEmpty) {
fromRequest = Option("0")
}
val from = Integer.parseInt(fromRequest.get) * 10
val to = from + 10
loadGameIds()
Ok(html.games(SteamStore.gamesIds(cache.getVal[JSONArray](GAME_KEY), from, to), cache.jsonArraySize(GAME_KEY)/10))
}


private def loadGameIds(): Unit = {
val games = cache.get(GAME_KEY)
if (games.isEmpty) {
get(s"$GAME_IDS_LIST_API", asJsonGamesId)
cache.set(GAME_KEY, lastResponse.get, 60.minutes)
}
}


What I would like is that loadGameIds would be invoked and cached when the class is instantiated.

Any suggestion?

Regards.

Answer

If I understand correctly your question, you simply want to add some statements to the main constructor body? If that's the case, you can simply do so in the body of the class itself. In your case, that would look like this:

class SteamController @Inject()(cache: CacheApi) extends BaseController {

  ...

  private val GAME_KEY: String = "games"

  loadGameIds() // <-- Here we are calling from the main constructor body

  def games = Action { implicit request =>
    ...
  }

  ...
}

When doing so, it is usually a good idea to perform additional code after the declaration of all vals and vars in your class, to ensure they are properly initialized at the time your additional constructor code runs.