java - 我无法理解 Java 8 中的一些 lambda 表达式

标签 java intellij-idea lambda casting java-8

我的代码片段看起来像这样,但没有使用 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() 中的类型转换来自postsFunction<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/

相关文章:

intellij-idea - 如何禁用 IntelliJ Idea 中的帮助?

sockets - 在 Intellij IDEA 中运行 Groovy 时出现奇怪的 java.net.SocketException Permission Denied 连接错误

Python lambda函数根据字典对列表进行排序

java - 读取文本文件并将其拆分为数组 - Android

java - 通过 id 搜索 xml 元素

java - 嵌套异常是 org.hibernate.exception.SQLGrammarException : could not extract ResultSet Hibernate+SpringMVC

c++ - 如何使用 boost bind 组合多个仿函数?

java - Log4j2 - Asynclogger Rolling File Appender 不是每天每小时滚动一次

java - Intellij 建议将类移动到(否则自动更正)检测到的包声明,如 Eclipse

c# - 如何在我的自定义集合中模仿 IQueryable<T>.Include(Expression<Func<T,TProperty>> path) 的功能?