Smart cast to 'ObserverT!!' is impossible because 'item.get()' is a complex expression

Viewed 254

I converted a Java code to Kotlin (Android Studio's automatic conversion) and I'm getting this error below:

enter image description here

The Java method looks like:

 /**
 * The list of weak reference to the observers.
 */
protected List<WeakReference<ObserverT>> observers = new ArrayList<>();

/**
 * Calls the specified action for each observer.
 * @param action action to be called.
 */
protected void foreachObserver(@NonNull final INotificationCallback<ObserverT> action) {
    final List<ObserverT> tempObserverList = new ArrayList<>();
    final List<WeakReference<ObserverT>> listToRemove = new ArrayList<>();
    synchronized (this) {
        if (!hasChanged()) {
            return;
        }
        clearChanged();

        if (observers.isEmpty()) {
            return;
        }

        for (final WeakReference<ObserverT> item : observers) {
            if (item.get() == null) {
                listToRemove.add(item);
            } else {
                tempObserverList.add(item.get());
            }
        }

        if (!listToRemove.isEmpty()) {
            observers.removeAll(listToRemove);
        }
    }
    notify(tempObserverList, action);
}

The converted code in Kotlin:

 /**
 * The list of weak reference to the observers.
 */
protected var observers: MutableList<WeakReference<ObserverT>> = ArrayList()

/**
 * Calls the specified action for each observer.
 * @param action action to be called.
 */
protected fun foreachObserver(@NonNull action: INotificationCallback<ObserverT>) {
    val tempObserverList: MutableList<ObserverT> = ArrayList()
    val listToRemove: MutableList<WeakReference<ObserverT>> = ArrayList()
    synchronized(this) {
        if (!hasChanged()) {
            return
        }
        clearChanged()
        if (observers.isEmpty()) {
            return
        }
        for (item in observers) {
            if (item.get() == null) {
                listToRemove.add(item)
            } else {
                tempObserverList.add(item.get()) // This line throws an error
            }
        }
        if (listToRemove.isNotEmpty()) {
            observers.removeAll(listToRemove)
        }
    }
    notify(tempObserverList, action)
}

I didn't find a solution to this as I don't understand it correctly. Any guidance will be appreciated.

Thanks for your time

1 Answers

Since item.get() doesn't necessarily stay the same between you checking it and adding it to the list, you should store it in a variable.

val x = item.get()
if (x == null) {
  listToRemove.add(item)
} else {
  tempObserverList.add(x) // No more error
}
Related