我在Kotlin中实现了AsyncTask
的子类:
class SignUpTask(responseHandler: SignUpTaskResponseHandler): AsyncTask<Agent, Void, Boolean>() {
override fun doInBackground(vararg params: Agent?): Boolean {
// Some awesome code
return true
}
override fun onPostExecute(result: Boolean?) {
result?.let {
if (it) {
responseHandler.agentCreationSucceeded()
} else {
// agent creation failed
}
}
}
}
问题是 - 我在此行responseHandler.agentCreationSucceeded()
处收到以下错误:
未解决的参考:responseHandler
我可以通过显式声明属性并为其赋予构造函数中传递的参数来使其工作:
class SignUpTask(responseHandler: SignUpTaskResponseHandler): AsyncTask<Agent, Void, Boolean>() {
val internalResponseHandler = responseHandler // explicit assignment to make it work inside onPostExecute
override fun doInBackground(vararg params: Agent?): Boolean {
// Some awesome code
return true
}
override fun onPostExecute(result: Boolean?) {
result?.let {
if (it) {
// Works only after explicit assignment?
internalResponseHandler.agentCreationSucceeded()
} else {
// agent creation failed
}
}
}
}
关于为什么会出现这种开销的任何想法,或者我错过了什么?
答案 0 :(得分:1)
你能试试吗?
let list = [{isDone:true}, {isDone:false}, {isDone:true}];
while (list.find(({isDone}) => isDone)) {
list.splice(list.indexOf(list.find(({isDone}) => isDone)), 1)
}
console.log(list);
原因是可变范围。 class SignUpTask(val responseHandler: SignUpTaskResponseHandler): AsyncTask<Agent, Void, Boolean>() {
override fun doInBackground(vararg params: Agent?): Boolean {
// Some awesome code
return true
}
override fun onPostExecute(result: Boolean?) {
result?.let {
if (it) {
// Works only after explicit assignment?
responseHandler.agentCreationSucceeded()
} else {
// agent creation failed
}
}
}
}
仅在类构造函数中定义。如果将其指定为val变量,则将其定义为类属性。