Egor Trutenko
02/07/2019, 1:04 AMContainer<String>
and Container<Int>
.
A one particular solution (although not really flexible) would to subtype Container<T>
with statically typed StringContainer : Container<String>
and IntContainer : Container<Int>
. The problem is, as aforementioned, it's not really flexible and we have to do it by hand.
What if we could somehow tell compiler that we want to generate such subclasses with statically saved type parameter for every class that uses original, generic class? E.g.
open class Container<sticky T> {
...
}
...
val sc = Container<String>()
if (sc is Container<Int>) { // unreachable }
Under the hood would turn into
val sc = StringContainer()
if (sc is Container) { ... }
Theoretically, it is possible to track down all the types which generic type is parameterized with in compile-time; To avoid some problems with subclassing this functionality could be restricted for non-final classes. Also there could be problems with multiple type parameters.
So, thoughts? Would this be useful, what more problems can this bring, is there ways to enhance it?Ruckus
02/07/2019, 2:47 PMClass<T>
, not to subclass Container
.Egor Trutenko
02/07/2019, 4:20 PMRuckus
02/07/2019, 4:25 PMclass Container<T>(val type: Class<T>)
Then you can just check the class
if (container.type == String::class.java) {
...
}
Ruckus
02/07/2019, 4:26 PMinline fun <reified T: Any> Container() = Container(T::class.java)
so you can still use
val sc = Container<String>()
elizarov
02/15/2019, 12:23 PMEgor Trutenko
02/18/2019, 10:52 AM