how to convert sealed class in kotlin to java

Viewed 159

I'm new to kotlin, how can I convert this kotlin code to java

sealed class TokenCommandResult {
    class Success(val response: OIDCTokenResponse) : TokenCommandResult()
    class Error(val error: TokenErrorResponse) : TokenCommandResult()
    class Fault(val exception: Throwable) : TokenCommandResult()
}


when (result) {
            is TokenCommandResult.Success -> printToken(format, result.response.oidcTokens.accessToken.value)
}

This is what I came up with, but I need repeat this code three times, is there a easier way to do that?

public static final class Success extends TokenCommandResult {      
      private final OIDCTokenResponse response;

      
      public final OIDCTokenResponse getResponse() {
         return this.response;
      }

      public Success( OIDCTokenResponse response) {
         
      }
   }
1 Answers

If you are using Java 16 or above, you can use sealed interfaces and records in Java to do roughly the same thing.

public sealed TokenCommandResult permits Success, Error, Fault {
    record Success(OIDCTokenResponse response) implements TokenCommandResult {}
    record Error(TokenErrorResponse error) implements TokenCommandResult {}
    record Fault(Throwable exception) implements TokenCommandResult {}
}

The amount of code this has is more comparable to the Kotlin version, but do note that a record class is more similar to a Kotlin data class rather than a regular Kotlin class.

If you are using something before Java 16, you can use Lombok to reduce the boilerplate:

@Getter
@AllArgsConstructor
public static final class Success extends TokenCommandResult {      
    private final OIDCTokenResponse response;
}
Related