在构造函数中调用方法
Call method in constructor
我有一个带有构造函数的控制器,我在其中注入缓存,但我也想在创建实例时调用构造函数中的方法。我知道我们可以用
创建一些辅助构造函数
def this(foo:Foo){}
但就我而言,因为游戏框架是我的 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)
}
}
我想要的是在实例化 class 时调用并缓存 loadGameIds。
有什么建议吗?
此致。
如果我对你的问题理解正确,你只是想在主构造函数体中添加一些语句?如果是这种情况,您可以简单地在 class 本身的主体中这样做。在你的情况下,它看起来像这样:
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 =>
...
}
...
}
这样做时,通常最好在 声明 class 中的所有 val 和 var 之后执行额外的代码,以确保它们是正确的在您的附加构造函数代码运行时初始化。
我有一个带有构造函数的控制器,我在其中注入缓存,但我也想在创建实例时调用构造函数中的方法。我知道我们可以用
创建一些辅助构造函数def this(foo:Foo){}
但就我而言,因为游戏框架是我的 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)
}
}
我想要的是在实例化 class 时调用并缓存 loadGameIds。
有什么建议吗?
此致。
如果我对你的问题理解正确,你只是想在主构造函数体中添加一些语句?如果是这种情况,您可以简单地在 class 本身的主体中这样做。在你的情况下,它看起来像这样:
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 =>
...
}
...
}
这样做时,通常最好在 声明 class 中的所有 val 和 var 之后执行额外的代码,以确保它们是正确的在您的附加构造函数代码运行时初始化。