我的代码片段看起来像这样,但没有使用 lambda 表达式:
.map(new Function<List<Post>, List<Post>>() {
@Override
public List<Post> apply(List<Post> posts) throws Exception {
return realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll();
}
})
.onErrorResumeNext(new Function<Throwable, ObservableSource<? extends List<Post>>>() {
@Override
public ObservableSource<? extends List<Post>> apply(Throwable throwable) throws Exception {
Log.d("rafael", throwable.getMessage());
return getLocalPostsObservable(userId, page);
}
})
使用 lambda 表达式(使用 Intellij 功能转换),它变成:
.map((Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll())
.onErrorResumeNext(throwable -> {
Log.d("rafael", throwable.getMessage());
return getLocalPostsObservable(userId, page);
})
我不明白为什么 map()
中的类型转换来自posts
至Function<List<Post>, List<Post>>
在
(Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll()
同时第二个表达式中没有类型转换:
throwable -> {
Log.d("rafael", throwable.getMessage());
return getLocalPostsObservable(userId, page);
}
最佳答案
What's the return type of
findAll()
?
我打赌 List<Post>
,根据Function<S, T>
的返回类型.
我的猜测是强制转换为 Function<S, T>
应用于整个 lambda 表达式,而不仅仅是 posts
参数及其返回值。
至于它存在的原因,可能是为了避免 map(FunctionLike<S, T>)
的歧义调用。 ;否则,代码生成工具添加一些无用的东西就不是第一次了。
关于java - 我无法理解 Java 8 中的一些 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44399491/