1

I was trying to implement CustomView in Kotlin, which is to be used both for programatically and for statically. Thus, I need to override both versions of constructors.

For programatically I use version,

class CustomView @JvmOverloads constructor(
   context: Context, 
) : View(context)

For statically I use version,

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

How can I change it for overriding multiple versions under same class which then I can instantiate from static views as well as programatically?

There are some post on constructors i.e. Kotlin secondary constructor which does not help for overriding multiple versions of constructor.

Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256

2 Answers2

1

This should work both programatically and statically :-

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

Programatically just call :-

CustomView(context) // passing other params to constructor is not mandatory..
Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
1

I created this code to recreate your issue:

Test.java:

public class Test {

    private int i ;
    private String name;

    public Test(int i) {
        this.i = i;
        name = "test";
    }

    public Test(int i, String name) {
        this.i = i;
        this.name = name;
    }
}

TestK.kt:

class TestK : Test {
    constructor(i: Int, name: String): super(i, name)
    constructor(i: Int) : super(i)
}

As you can see, I'm overloading the parents constructor with different parameter amounts.

Purfakt
  • 101
  • 1
  • 16
  • 1
    I can't comment on @santanu-sur answer, but in my opinion, it isn't exactly answering the question on how to overload several constructor. You're passing default value to the 3 arguments constructor, but that might not always be what we want. (Case of different constructor implementation.) – Purfakt Jun 11 '19 at 10:24