how could I run some code after constructor like i...
# android
c
how could I run some code after constructor like in Java?
Copy code
public class CustomView extends View {
    public CustomView(Context context) {
        this(context,null);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //some custom code
    }
}
I try
init{}
block, but it run before constructor.
Copy code
class CustomView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    init {
        // this place is run before super constructor
    }
}
k
Copy code
class CustomView : View {
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        //some custom code
    }
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs, 0) {
    }

    constructor(context: Context?) : super(context) {
    }
}
@CodeIdeal This is the other way to implement the same code. Hope this helps.
👍 1
i
Nothing is ever run before the super constructor. That isn't allowed on the JVM, whether you write you code in Java or Kotlin
👍 2
c
@Kavita is there any way to complete this with in @JvmOverloads annotation.
k
Hi @CodeIdeal, We use @JvmOverloads annotation in Kotlin for interoperating with Java code. Here if you are implementing View class's constructor traditionally, then there is no need to use @JvmOverloads.