08/30/2019, 6:51 AM
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:
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,
            .apply {
                hideIcon = getBoolean(R.styleable.IconItemView_icon_item_hide_icon, true)
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?

Amirul Zin

08/30/2019, 7:08 AM
Practically, it’ll be something like this:
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

Eric Martori

08/30/2019, 1:38 PM
If the value of the boolean is defined at contruction time you can just initialize it with the value:
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,, true)