在内部类Kotlin中获得局外人价值

时间:2019-02-28 05:52:56

标签: android kotlin

对不起,我是Kotlin的新手,所以请多多包涵。

我有这个代码

 Class A :Basefragment()
    {
        ...

        override fun onOptionsItemSelected(item: MenuItem): Boolean {
            val id = item.itemId

            if (id == R.id.save) {
                val thread = SimpleThread(editTitle.text.toString(), editDescription.text.toString())
                thread.start()
            }
        }

        inner class SimpleThread(title: String, description: String) : Thread() {
            override fun run() {
                var titles = title // how to use title ?
            }

        }
    }

在SimpleThread中,如何获取标题值?我得到未解决的引用

1 个答案:

答案 0 :(得分:2)

您当前的语法仅将titledescription作为构造函数参数传递,您可以使用它们来初始化属性或在init块中:

inner class SimpleThread(title: String, description: String) : Thread() {
    val title = title

    init {
        println(description)
    }
}

虽然您可以将这些值保存到如上所述的属性中,但也可以将valvar直接添加到构造函数中,以创建采用构造函数参数值的属性:

inner class SimpleThread(val title: String, val description: String) : Thread() { ... }

现在可以随时通过任何功能访问这些保存的属性,而不仅仅是在构造时。