Observable <list <对象>>不能转换为Observable <list <动漫>>

时间:2018-11-28 11:20:40

标签: java android android-studio

我收到错误消息“类型不兼容:Observable<List<Object>>无法转换为Observable<List<Anime>>

public Observable<List<Anime>> getOnlyAnimeObservable() {
    List onlyAnimeList = getOnlyAnimeList();
    if (onlyAnimeList == null) {
        return Observable.just(Collections.emptyList());  //Required <List<Class>> But Found <List<Object>>
    }
    return Observable.just(onlyAnimeList); //Required <List<Class>> But Found <List>
}

如果我将public Observable<List<List<Anime>> getOnlyAnimeObservable()更改为

public Observable<List<Object>> getOnlyAnimeObservable() 
  

返回Observable.just(Collections.emptyList()); 错误已解决,但返回Observable.just(onlyAnimeList); 仍然显示错误

同时我将public Observable<List<List<Anime>> getOnlyAnimeObservable()更改为public Observable<List> getOnlyAnimeObservable()

  

返回Observable.just(onlyAnimeList); 错误已解决,但返回Observable.just(Collections.emptyList()); 显示错误。

1 个答案:

答案 0 :(得分:1)

是因为Collections.emptyList()返回了List<Object>。尝试以下代码:

List<Anime> list = Collections.emptyList();
return Observable.just(list);

getOnlyAnimeList方法也应返回List<Anime>类型。因此完整的代码应该是:

 public Observable<List<Anime>> getOnlyAnimeObservable() {
    List<Anime> onlyAnimeList = getOnlyAnimeList();
    if (onlyAnimeList == null) {
        List<Anime> list = Collections.emptyList();
        return Observable.just(list);
    }
    return Observable.just(onlyAnimeList);
 }

我们可以简化一切:

public Observable<List<Anime>> getOnlyAnimeObservable() {
    List<Anime> list = getOnlyAnimeList();
    if (list == null) {
        list = Collections.emptyList();
    }
    return Observable.just(list);
}