'reified' constructor type parameters ? Possible ?...
# announcements
d
'reified' constructor type parameters ? Possible ? I have a set of classes that use reflection and require the KClass object for the 'type' of the class - this is a GUI class that shows a list or edit form for a type. Rougly: class BaseView<T>( val kclass : KClass<T> ) { } class FormView : BaseView<AFormType>( AFormType::class ) { ... } I'd like to get rid of either the need for the constructor parameter and/or the need to explicitly pass it e.g. this would be nice class BaseView<T>( val kclass : KClasss<T> = T::class ) // inline constructor<reified T> ??? Is this possible ? I can make a function that does this but I cant derive from it -- (?) fun <reified T> BaseView() = BaseView<T>(T::class) --> but how to derive ? Any suggestions ?
a
reified is not supported in constructors (yet)
d
Yes. Is there an alternative way to achive something similar ?
a
what you can do is, you can accept KClass (or java class) in the constructor
d
Yes. Thats what Im doing. Would like to avoid that. A class delegate by function might work but its not the same and would require interfaces -- class View<T>: BaseView<T> by reifiedFunction<T>() { }
If that worked then so would a constructor default value by reified function
a
the only thing you can do is create an extension function to achieve this. Something like
Copy code
reified fun View()...
d
This see3ms to work --
abstract class X<T:Any>() {
val x : Int = 1
abstract fun getView() : KClass<T>
}
inline fun <reified T:Any>  X<T>.view() = T::class
class Y : X<StatementJob>() {
override fun getView() = view()
}
Not exactly simplier -- but maybe a way to morph it into something
s
You can use smart-constructors:
Copy code
class MyClass private constructor(...) {

    companion object {
        inline operator fun <reified T> invoke(...): MyClass {
        }
    }
}
Then you can construct it still like this
val mc = MyClass(…)
, because it is the same as
val mc = MyClass.invoke(…)
👍 3
d
Yes. But that only works when the call is not the constructor itself. I.e. you cant derive from a class that requires the type parameter and a class instance in the constructor, So like my method, one has replace a bit of clumbsy boilerplate with a LOT of clumbsy boilerplate -- it didnt go away.
easier to make a global reified function of the same name -- for cases that you dont need it to be a 'constructor' literlly - just look like one in some cases.