how could i initialize val in a method provided th...
# android
o
how could i initialize val in a method provided that method is only called from constructor? For example, I'm writing custom View like that:
Copy code
class IconItemView : LinearLayout {

    private var hideIcon: Boolean = true

   constructor(context: Context): this(context, null)

    constructor(context: Context, attributes: AttributeSet?): this(context, attributes, 0)

    constructor(context: Context, attributes: AttributeSet?, defStyleAttr: Int): super(context, attributes, defStyleAttr) {
        init(context, attributes, defStyleAttr)
    }

   private fun init(context: Context, attributes: AttributeSet?, defStyleAttr: Int) {
        context.obtainStyledAttributes(attributes, R.styleable.IconItemView, defStyleAttr, R.style.IconItemView)
            .apply {
                hideIcon = getBoolean(R.styleable.IconItemView_icon_item_hide_icon, true)
                recycle()
            }
    }
Property hideIcon is essentially final, since it's only assigned in constructor, though there are *init*ialization method inside. I dont want to pass the whole method body to one of constructors, but Kotlin neither allows to have that init() fuctions as a local function in ctor, nor to make hideIcon properly as val Is there any way to make the property final?
a
Practically, it’ll be something like this:
Copy code
class IconItemView @JvmOverloads constructor(
  val hideIcon: Boolean = true,
  context: Context,
  attr: AttributeSet? = null,
  defStyle: Int = 0
): LinearLayout(context,attr,defStyle){
  init {
      attr?.let {
        hideIcon = false //compile error
        //your code
      }
  }
}
4
e
If the value of the boolean is defined at contruction time you can just initialize it with the value:
Copy code
class IconItemView @JvmOverloads constructor(
    context: Context,
    attr: AttributeSet? = null,
    defStyle: Int = 0
) : LinearLayout(context, attr, defStyle) {
    val hideIcon: Boolean = context.obtainStyledAttributes(attr, R.styleable.IconItemView, defStyleAttr, R.style.IconItemView).getBoolean(R.styleable.IconItemView_icon_item_hide_icon, true)
}