通过kotlin中的匿名内部对象修改外部类

我正在Kotlin写我的第一个Android应用程序。

我想要做的是发出一个HTTP请求(排空),以获取一些数据,应写入对象的属性。
直到Volley响应监听器被保留为止,这一切都工作的很好。 之后,属性返回null。

这是来电者:

class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val haiku = Haiku(applicationContext) haiku.load() // populates 3 properties (author, body, title) haiku.show() // author, body, title are back to null here } } 

被调用者:

 class Haiku(var context: Context? = null, var title: String? = null, var body: String? = null, var author: String? = null) : Parcelable { // parcelable implementaion left out here fun load() { val stringRequest = object : StringRequest(Request.Method.GET, EndPoints.URL_GET_HAIKU, Response.Listener { response -> try { val json = JSONObject(response) // proper payload arrives val haiku = json["haiku"] as JSONObject this@Haiku.title = haiku["title"] as String // all properties look alright here this@Haiku.author = haiku["author"] as String this@Haiku.body = haiku["body"] as String } catch (e: JSONException) { Toast.makeText(context, R.string.haiku_not_fetched, Toast.LENGTH_LONG).show() } }, Response.ErrorListener { error -> Toast.makeText(context, R.string.haiku_not_fetched, Toast.LENGTH_LONG).show() }) { } VolleySingleton.instance?.addToRequestQueue(stringRequest) } fun show() { // when called after the load method title, body, author are back to null val intent = Intent(context, HaikuDisplayActivity::class.java) intent.putExtra(EXTRA_HAIKU, this) context!!.startActivity(intent) } } 

对象的范围可能是一个问题,但我无法弄清楚为什么值不能保存。 非常感谢您的帮助!

这个问题在评论中得到了回答。 当show()方法被调用时,HTTP请求还没有返回。 调试器让我感到困惑,因为它看起来已经在那里了。

谢谢@Chisko