Java compilation error when using switch expression in a lambda

XMLWordPrintable

    • generic

      this code works:

              homeService.setHome(playerId, homeName, location).thenAccept(result -> {
                  sender.sendMessage(switch (result) {
                      case SetHomeResult.Created() -> messageService.homeCreated(homeName);
                      case SetHomeResult.Replaced(var oldHome) ->
                          messageService.homeReplaced(playerId, oldHome);
                      case SetHomeResult.LimitReached(var limit) ->
                          messageService.homeLimitReached(limit);
                  });
              });

      on the other hand, this code:

              homeService.renameHome(playerId, homeName, newName).thenAccept(result -> sender.sendMessage(switch (result) {
                  case RenameHomeResult.Renamed(var oldName) -> messageService.homeRenamed(oldName, newName);
                  case RenameHomeResult.NotFound() -> messageService.homeNotFound(homeName);
              }));

      does not compile

      Reproducing Steps:
      Use CompletableFuture.thenAccept with an anonymous inner function that uses a switch expression as an argument to another function. If this is relevant, the value being switched over is of the type of a sealed interface.

      Workaround:
      Wrapping the switch expression in a block resolves the issue.

            Assignee:
            Chen Liang
            Reporter:
            Robert Mckenna
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: