Heinrisch
Heinrisch

Reputation: 5935

Hiding view default constructors

Is there a way in Kotlin to hide (place somewhere else) the default constructors of a view? Maybe creating a subview or extension or something similar.

Currently all my views look like this, which is a little verbose:

class MyView(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int): View(context, attrs, defStyleAttr, defStyleRes) {
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): this(context, attrs, defStyleAttr, 0)
    constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0, 0)
    constructor(context: Context): this(context, null, 0)
}

Upvotes: 2

Views: 247

Answers (2)

voddan
voddan

Reputation: 33849

More or less proper formatting for the @udalov's answer:

class MyView(context: Context, 
             attrs: AttributeSet? = null, 
             defStyleAttr: Int = 0, 
             defStyleRes: Int = 0) : View(context, attrs, defStyleAttr, defStyleRes)

or

class MyView @JvmOverloads constructor(
        context: Context, 
        attrs: AttributeSet? = null, 
        defStyleAttr: Int = 0, 
        defStyleRes: Int = 0
) : View(context, attrs, defStyleAttr, defStyleRes) {
    // ....
}

Upvotes: 1

Alexander Udalov
Alexander Udalov

Reputation: 32826

You can use default arguments:

class MyView(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0): View(context, attrs, defStyleAttr, defStyleRes)

In case you need to invoke these constructors from Java, consider applying the @JvmOverloads annotation to the constructor:

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

Upvotes: 6

Related Questions