Java8 - “有效最终” [英] Java8 - "effectively final"
本文介绍了Java8 - “有效最终”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用RxVertx这是一种RxJava和Java8,我有一个编译错误。
I'm using RxVertx which is a sort of RxJava along with Java8 and I have a compilation error.
这是我的代码:
public rx.Observable<Game> findGame(long templateId, GameModelType game_model, GameStateType state) {
return context.findGame(templateId, state)
.flatMap(new Func1<RxMessage<byte[]>, rx.Observable<Game>>() {
@Override
public Observable<Game> call(RxMessage<byte[]> gameRawReply) {
Game game = null;
switch(game_model) {
case SINGLE: {
ebs.subscribe(new Action1<RxMessage<byte[]>>() {
@Override
public void call(RxMessage<byte[]> t1) {
if(!singleGame.contains(0) {
game = new Game(); // ERROR is at this line
singleGames.put(0, game);
} else {
game = singleGames.get(0); // ERROR is at this line
}
}
});
}
}
return rx.Observable.from(game);
}
});
}
编译错误是:
本地变量游戏定义为封闭范围必须是最终的或有效的最终结果
The compilation error is: "Local variable game defined in an enclosing scope must be final or effectively final"
我无法将'游戏'定义为最终,因为我执行allocation \set并在函数结束时返回它。
I cannot define 'game' as final since I do allocation\set and return it at the end of the function.
如何编译此代码?
谢谢。
推荐答案
我有一个 Holder
类,用于这种情况。
I have a Holder
class that I use for situations like this.
/**
* Make a final one of these to hold non-final things in.
*
* @param <T>
*/
public class Holder<T> {
private T held = null;
public Holder() {
}
public Holder(T it) {
held = it;
}
public void hold(T it) {
held = it;
}
public T held() {
return held;
}
public boolean isEmpty() {
return held == null;
}
@Override
public String toString() {
return String.valueOf(held);
}
}
然后您可以执行以下操作:
You can then do stuff like:
final Holder<Game> theGame = new Holder<>();
...
theGame.hold(myGame);
...
{
// Access the game through the `final Holder`
theGame.held() ....
这篇关于Java8 - “有效最终”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文