KotlinLifeguard #1
Daniel Gomez RicoUsing @JvmOverloads tag helps to avoid multiple constructors with Kotlin
The headache
It’s really possible that you had some code like:
class MyCustomView : FrameLayout {
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int)
: super(context, attrs, defStyleAttr) {
init()
}
fun init() {
// ...
}
}
As you can see there are all the constructors needed for a custom FrameLayout
but all with same “body”.
The remedy
Refactored with @JvmOverloads
:
class MyCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: FrameLayout(context, attrs, defStyleAttr){
init {
// ...
}
}