How to create constructor of custom view with Kotlin

Kotlin supports multiple constructors since M11 which was released 19.03.2015. The syntax is as follows:

class MyView : View {
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        // ...
    }
 
    constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0) {}
}

More info here and here.

Edit: you can also use @JvmOverloads annotation so that Kotlin auto-generates the required constructors for you:

class MyView @JvmOverloads constructor(
    context: Context, 
    attrs: AttributeSet? = null, 
    defStyle: Int = 0
) : View(context, attrs, defStyle)

Beware, though, as this approach may sometimes lead to the unexpected results, depending on how the class you inherit from defines its constructors. Good explanation of what might happen is given in that article.


You should use annotation JvmOverloads (as it looks like in Kotlin 1.0), you can write code like this:

class CustomView @JvmOverloads constructor(
    context: Context, 
    attrs: AttributeSet? = null, 
    defStyle: Int = 0
) : View(context, attrs, defStyle)

This will generate 3 constructors just as you most likely wanted.

Quote from docs:

For every parameter with a default value, this will generate one additional overload, which has this parameter and all parameters to the right of it in the parameter list removed.