Property initialized with generic type parameter can not hold the same type value

I’m trying to achieve the following but I’m getting error. Trying to understand what’s going wrong here and what should be done to get around the error. I want to support both nullable and non-nullable here.

class TriggeredLiveData<T, V>(value: V) : LiveData<V>(value) {
  private val trigger = MutableLiveData<T>()
  ...
  fun pullTrigger(payload: T) {
    trigger.postValue(payload) // Error: Expected non-nullable value
  }
}

Also here is the signature for both MutableLiveData and LiveData

public class MutableLiveData<T> extends LiveData<T> {

    /**
     * Creates a MutableLiveData initialized with the given {@code value}.
     *
     * @param value initial value
     */
    public MutableLiveData(T value) {
        super(value);
    }

    /**
     * Creates a MutableLiveData with no value assigned to it.
     */
    public MutableLiveData() {
        super();
    }

    @Override
    public void postValue(T value) {
        super.postValue(value);
    }

    @Override
    public void setValue(T value) {
        super.setValue(value);
    }
}
public abstract class LiveData<T> {
  ...
  protected void postValue(T value) { ... }
}
1 Like

Short answer: I can’t see an immediate reason for the error.⠀My guess would be that you have a setting, maybe in your IDE or build tool, telling Kotlin to treat Java values as non-nullable unless annotated otherwise.

Slightly longer answer:

In the code you quote, the LiveData and MutableLiveData classes are in Java; they don’t have any restrictions on the type parameter, so it has an upper bound of Object (which is nullable in Java).

In the absence of any annotations specifying the nullability of postValue()'s parameter (such as @NonNull or @Nullable), Kotlin normally treats it as a ‘platform type’ (i.e. one whose nullability isn’t known).

So it would normally allow you to pass a value that could be null.⠀(There might be a warning, but not an error.)⠀But there are options you can set to change that behaviour (e.g. these), and that would be my best guess as to why you’re seeing an error.⠀If so, then changing that option would fix the problem.

Alternatively, if the Java code is under your control, you could add nullability annotations.⠀(That would have wider benefits, too — for the correctness of the Java code as well as the convenience and safety of Kotlin calling it.)