构造函数中的调用方法

时间:2016-10-01 19:12:50

标签: scala playframework playframework-2.0

我有一个带有构造函数的Controller,我注入了一个缓存,但是我想在创建实例时在构造函数中调用一个方法。我知道我们可以使用

创建一些辅助构造函数
def this(foo:Foo){}

但在我的情况下,因为是play框架实例我的bootstrap有点复杂。

这是我的代码

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)
    }
  }

我想要的是,在实例化类时,将调用loadgameIds并缓存它。

有什么建议吗?

问候。

1 个答案:

答案 0 :(得分:6)

如果我理解你的问题,你只想在主构造函数体中添加一些语句?如果是这种情况,您可以在本身中执行此操作。在您的情况下,这将是这样的:

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 =>
    ...
  }

  ...
}

这样做时,通常在声明类中所有val和vars之后执行其他代码,以确保在其他构造函数代码运行时正确初始化它们