JT
09/27/2018, 11:19 PMorangy
JT
09/28/2018, 12:52 AMpublic class MyBaseClass {
public MyBaseClass() {}
public MyBaseClass(Map<String, String> attrs) {
processAttribute(attrs);
}
protected void processAttribute(Map<String, String> attrs) {
}
}
class MyKotlinClass @JvmOverloads constructor(attrs: Map<String, String>? = null) :
MyBaseClass(attrs) {
companion object {
const val COLLAPSED_LINES = "CollapsedLines"
const val DEFAULT_COLLAPSED_LINES = 3
}
private var collapsedMaxLines = DEFAULT_COLLAPSED_LINES
override fun processAttribute(attrs: Map<String, String>) {
super.processAttribute(attrs)
processExpandableAttrs(attrs)
}
fun getCurrentCollapsedLines() = collapsedMaxLines
private fun processExpandableAttrs(attrs: Map<String, String>) {
collapsedMaxLines = attrs[COLLAPSED_LINES]?.toInt() ?: DEFAULT_COLLAPSED_LINES
}
}
val myClass = MyKotlinClass(mapOf(MyKotlinClass.COLLAPSED_LINES to "5"))
var maxLines = myClass.getCurrentCollapsedLines()
Where MyBaseClass's constructor calls processAttribute. If I set breakpoints I see the value change from 3 (DEFAULT_COLLAPSED_LINES) to the value I set in the attributes, but when I later access it - it's back to 3. If I change the variable declaration to use a hardcoded number private var collapsedMaxLines: Int = 0
(instead of the companion object constant) , if I set a breakpoint, again the number gets assigned to the attribute I pass in, and stays assigned when I access it later.JT
09/28/2018, 1:10 AMorangy
MyKotlinClass
is created, it first calls super
constructor, and you have a call to processExpandableAttrs
before initialization for MyKotlinClass
continues. It will be the same in you write this class in Java. Zero is the default value for the Int
type, so compiler doesn’t put a write to collapsedMaxLines
backing field into `MyKotlinClass`’s constructor.orangy
processExpandableAttrs
and on the collapsedMaxLines
and see yourself what goes on.JT
09/28/2018, 6:58 PM