Can't dip into some lambda expressions in Java 8
I have this piece of code that looks like this without using lambda expressions:
.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);
}
})
Using a lambda expression (converted using Intellij function) it becomes:
.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);
})
What I don't understand is why the fill type in map()
from posts
to Function<List<Post>, List<Post>>
to
(Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll()
At the same time, there is no casting in the second expression:
throwable -> {
Log.d("rafael", throwable.getMessage());
return getLocalPostsObservable(userId, page);
}
source to share
What type of return
findAll()
?
I would bet on List<Post>
according to the return type Function<S, T>
.
My guess is that the cast to Function<S, T>
applies to the entire lambda expression, not just the parameter posts
, but also the return value.
Because of his presence, perhaps ambiguous challenge should be avoided map(FunctionLike<S, T>)
; otherwise the code generation tool won't add some useless stuff the first time.
source to share
These are not tags posts
, but the whole lambda expression, and since it does not fail compilation, we can infer that it posts
has a type List<Post>
and findAll
also returns List<Post>
.
Could it be due to chaining, for example:
where(..).equalTo(..).findAll(..)
You can check if this is the case by taking this code inside the method that returns List<Post>
, and inside your lambda expression use that method instead. If intelli doesn't add a cast, there is a problem.
source to share