How to create generic object in base class for derived class

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
    }

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,

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,

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

1 Like

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.