Suppose I have the following class, with a type parameter T (in this example it's bounded to help illustrate a later example, but the error persists when it's unbounded):
class GenericsTest<T : CharSequence>(private var cs: T)
Now suppose I want to add a secondary constructor to this class. How can I do this? My first (naive) attempt resulted in a compiler error:
class GenericsTest<T : CharSequence>(private var cs: T)
{
// dummy exists to ensure the method signatures are different
constructor(cs: String, dummy: Int) : this("a")
}
IntelliJ underlines "a" with the message:
Type mismatch.
Required: T
Found: String
To me, String seems to be a perfectly valid T. I thought explicitly specifying the type parameter would help, but that doesn't seem to be allowed. Both of these attempts are incorrect syntax:
constructor(cs: String, dummy: Int) : this<String>("a")
constructor<U : String>(cs: U, dummy: Int) : this("a")
Since I suspect that there's a common approach to all of these scenarios, my main question is:
How do you write secondary constructors for a generic class in Kotlin? Or similarly, how do you delegate to the primary constructor when the constructor has type parameters?
Is this even possible? If not, one workaround might be to use a helper function to create the object using the primary constructor, but this wouldn't work for e.g. abstract classes.
The official documentation on generics doesn't discuss constructors.