Heinrisch Heinrisch - 4 months ago 8
Android Question

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)
}

Answer

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.