I have a base class ,it need create generic object for derived class, when i code it in java ,i can generate the object from nonargs constructor as init,i use IDEA to convert the Java code to Kotlin code, i think lateinit var model :T
is much more suitable to private var model: T? = null
,but when i use lateinit
the IDEA will tell me there is an error :
can I make the Kotlin code more Kotlin?
my Java code:
public class CommonAction<T> extends ActionSupport implements ModelDriven<T> {
private T model;
public T getModel() {
return model;
}
public CommonAction() {
ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
Class<T> entityClass = (Class<T>) actualTypeArguments[0];
try {
model = entityClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
the Kotlin code:
open class CommonAction<T> : ActionSupport(), ModelDriven<T>, ServletResponseAware {
private var model: T? = null
override fun getModel(): T? = model
init {
val genericSuperclass = this.javaClass.genericSuperclass as ParameterizedType
val actualTypeArguments = genericSuperclass.actualTypeArguments
val entityClass = actualTypeArguments[0] as Class<*>
model = entityClass.newInstance() as T
}