Simple Constructors for Inheritance

When I create a custom FrameLayout I need to implement those 3 constructors but as you see all of them just call super(...) and init().

class VideoView : 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(){ ... }
  
}

Is there any way to make it cooler?
Maybe an annotation like all constructors call init() and it will generate all the constructors calling init?

1 Like

You can use @JvmOveloads annotation and common init {} block

class VideoView @JvmOverloads constructor(
        context: Context, 
        attrs: AttributeSet? = null, 
        defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    
    init { ... }

}
7 Likes