Hi guys, is there a way to have a secondary constr...
# announcements
j
Hi guys, is there a way to have a secondary constructor with own (more specific) generic type ?
I'd like to do something like this
Copy code
class View{}
interface XYZ { }
class XYZView extends View implements XYZ { }

class MyClass<T extends View> {
    public MyClass(T view, XYZ xyz) {
    }

    public <X extends View & XYZ> MyClass(X x) {
        this((T)x, x);
    }
}

public static void main(String[] args) {
    new MyClass(new View(), new XYZ() {});
    new MyClass(new XYZView());
}
s
as best as I can tell, Kotlin doesn’t support having disparate call-site generics specified in secondary constructors (i.e. where the generic on the constructor is detached from the generic on the class) but, have no fear, the factory method takes care of what you want:
Copy code
open class View
interface XYZ
class XYZView : View(), XYZ

class MyClass<T : View>(view: T, xyz: XYZ) {
  companion object {
    operator fun <X> invoke(x: X): MyClass<X>
        where X : View, X : XYZ {
      return MyClass(x, x)
    }
  }
}

fun main() {
  MyClass(View(), object : XYZ {})
  val xyzClass: MyClass<XYZView> = MyClass(XYZView())
}
👍 1