初始化后属性被擦除 – kotlin
我正在使用Kotlin在Android项目中工作。 我有这段代码:
val foo = FooClass(this) var colorRunning = FooClass.getProperty("myproperty")
和类FooClass
是:
class FooClass(val context: Context) : SomeHeritance{ private val styles: HashMap = hashMapOf() override fun onCreate(context: Context?) { Log.e("Hash is empty here", this.styles.size.toString()) this.styles.put("a","a") this.styles.put("b","a") this.styles.put("c","a") Log.e("Hash is size is 3", this.styles.size.toString()) } override fun getProperty(someProp: String) { Log.e("Hash is size is 0", this.styles.size.toString()) //I don't understand why return styles[someProp]!! }
问题是HashMap
styles
在onCreate
方法中初始化,但是当我想从getPropery
方法访问一些值时, HashMap
是空的。
做一些测试,我可以检查,如果我初始化方法getProperty
HashMap
哈希仍然初始化。
看起来像你的onCreate
不被称为开始。 把你的Map
的init
放在一个init
块中:
init { with(styles){ put("a","a") put("b","a") put("c","a") } }
这样,您可以确保在访问之前将值存入地图。
另外,请确保正确地处理getProperty
null
值。 而不是!!
你可以抛出一个例外:
fun getProperty(someProp: String): String = styles[someProp] ?: throw IllegalArgumentException()