Is there a way to constrain type parameters like this? In this case I’m using kotlinx serialization, so want to say that the type T
has the given static/companion method to get the serializer.
fun <T> HttpServletResponse.respondSerializable(x: T) {
val serializer = T.serializer() // ???
val jsonString = Json.stringify(serializer, x)
this.writer.write(jsonString)
}
Hello. Kotlin can’t constrain type parameters like that. Error message for reference: [TYPE_PARAMETER_ON_LHS_OF_DOT] Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left hand side of dot
.
You’re welcome to submit an issue at http://kotl.in/issue describing your use case. If it turns out that this is mainly needed for serialization, maybe this could be supported as a special case in the serialization compiler plugin.
Thanks. I was trying to understand the language, but I don’t have a strong use case yet. If I find one I will of course file an issue to let you know.