How to create generic object in base class for derived class


#1

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 :hint

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
    }


#2

lateinit is a workaround that lets you not initialize a non-nullable value. It’s like saying: "This will never be null, but I don’t have the initial value yet. Trust me, I will assign the value before it will be used. You can Null Pointer Exception me if Idon’t."
But if the value is nullable, there is no point in using lateinit. Not being initialized is perfectly valid state for that value already,


#3

thanks for answer,this is my point too, I don’t want see the value is nullable declaration,the object model will never be null,but i have no idea what can I do with the lateinit for my code,


#4

You need to declare a constraint for the type parameter: open class CommonAction<T : Any>


#5

It works! Thank you! I have no idea what to do with the hint “‘lateinit’ modifier is not allowed on properties of a type with nullable upper bound” before.