Java8 - "有效最终"

Shv*_*alb 4 java lambda java-8 rx-java

我正在使用RxVertx这是一种RxJava和Java8,我有一个编译错误.

这是我的代码:

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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

编译错误是:"在封闭范围内定义的局部变量游戏必须是最终的或有效的最终"

我不能将'游戏'定义为最终,因为我在分配\ set并在函数结束时返回它.

我怎样才能编译这段代码?

谢谢.

Old*_*eon 6

我有一个Holder课程,我用于这样的情况.

/**
 * 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);
  }

}
Run Code Online (Sandbox Code Playgroud)

然后你可以做以下事情:

final Holder<Game> theGame = new Holder<>();
...

theGame.hold(myGame);
...
{
  // Access the game through the `final Holder`
  theGame.held() ....
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用AtomicReference. (3认同)
  • 对于`toString`方法,你实际上可以做`String.valueOf(hold)`如果字符串为null则返回"null",如果不是则调用`hold.toString()`. (2认同)