lambda表达式中的错误返回类型无法将Object转换为T.

时间:2017-04-23 13:26:46

标签: java generics lambda

我有这个懒惰的迭代器,几乎接收函数和字符串作为参数,转到API,从API接收DTO并将该DTO转换为域对象(在本例中为事件)。如下所示,此活动由艺术家和多个曲目组成。我的问题(不仅仅是这里)是,在我的EventIterator中,我尝试通过传递一个lambda表达式填充我的artistSupplier,我得到错误" lambda表达式中的错误返回类型ArtistD不能转换为T"

public class EventIterator<T, U, R> extends SetListIterator<T, U, R> implements Iterator<R> {

private Function<U, T[]> function;
private String s;
private LastfmApi lastfmApi;

public EventIterator(String s, Function<U, T[]> function, LastfmApi lastfmApi) {
    this.lastfmApi = lastfmApi;
    this.s = s;
    this.function = function;
    page = 1;
}

@Override
public R convertToDomainType(T[] ret) {
    EventDto [] eventDtos = (EventDto[]) ret;
    LinkedList list = new LinkedList<Event>();
    for (EventDto e:
         eventDtos) {
        Event event = new Event(
                e.getArtistName(),
                e.getEventDate(),
                e.getTour(),
                e.getTracksNames(),
                getTracks(e.getTracksNames(), e.getArtistName()),
                e.getSetListId()
         );
        event.setArtistSupplier(
                (b, c) -> new ArtistIterator<R, U, T>(
                        e.getArtistName(),
                        (a) -> lastfmApi.getArtistInfo(e.getArtistName())
                )
        );
        list.add(event);
    }
    return (R) list;
}


public class Event {

private Artist artist;
private Function<String, Artist> artistSupplier;
private String artistName;
private String eventDate;
private String tour;
private String [] tracksNames;
private Iterable<Track> tracks;
private String setlistId;

public void setArtistSupplier(Function<T, U> supplier) {
    this.artistSupplier = supplier;
}

public Artist artist(String s) {
    return artist = (Artist) artistSupplier.apply((T) s);
}

}

public class Artist {

private String name;
private String bio;
private String url;
private String [] imagesUri;
private String mbid;

}

public abstract class SetListIterator<T, U, R> implements Iterator<R> {

protected String s;
protected int page;
protected T []dtos;

@Override
public R next() {
    T[] ret = dtos;
    if (!hasNext())
        throw new NoSuchElementException();
    dtos = moveNext();
    return convertToDomainType(ret);
}

public abstract T[] moveNext();

public abstract R convertToDomainType(T[] ret);
}

1 个答案:

答案 0 :(得分:1)

当您尝试传递一些接受两个参数{{1}的函数时,您的artistSupplier函数被定义为Function<String, Artist>,其中包含String个输入和Artist输出}并返回(b,c)

ArtistIterator

由于您的代码确实包含event.setArtistSupplier( (b, c) -> new ArtistIterator<R, U, T>( e.getArtistName(), (a) -> lastfmApi.getArtistInfo(e.getArtistName()) ) ); 实现,我可以假设它是这样的:

Event#setArtistSupplier

修改

您需要做的是:

setArtistSupplier(Function<String,Artist> function) {artistSupplier = function;}