I’d love to see reified constructors so that I hav...
# language-proposals
m
I’d love to see reified constructors so that I have all information about generic type parameters. I’d use them to replace problematic Java type token hacks when writing BSON/JSON/GraphQL serializer base classes. And it would even work in multiplatform!
Copy code
open class Generic<T: Any> private constructor(
   private val type: KType
) {

   inline <reified T> constructor():
      this(type = typeOf<T>())
}
Does anyone else have good use cases for this?
👍 2
s
Do you gain anything else than some sugar so you wont have to write the companion invoke function yourself?
m
This won’t work with companions
class SomeClass: Generic<List<String?>>()
👍 1
d
I'm using this as a workaround:
Copy code
@Suppress("FunctionName")
inline fun <reified T> SomeClass(): SomeClass<T>() {
  return SomeClass(typeOf<T>())
}

class SomeClass<T>(val type: KType)
(I see you already mentioned it before in the ticket)
👀 1
m
I would have to do that for hundred of classes 😅 Also, in my current use case all are
object
, so that workaround won’t work. My current workaround is that each
object
has to call an extension function during initialization which allows me to generate a
KType
e
This got me thinking but maybe we can have a
fun constructor(): SomeClass {...}
that generates a ‘static’ (or top level in kotlin terms) function with same name as class. Should be possible to make it inline and have reified type params