Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate sealed classes using annotation processor #64

Closed
tonivade opened this issue Jun 3, 2020 · 0 comments
Closed

Generate sealed classes using annotation processor #64

tonivade opened this issue Jun 3, 2020 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@tonivade
Copy link
Owner

tonivade commented Jun 3, 2020

For example, in Option interface, we want to make sure that only two implementations of Option are available, Some and None.

Right now I'm doing a trick to forbid other classes may implement the Option interface.

@HigherKind
public interface Option extends OptionOf<T> {

  OptionModule getModule();

  final class Some implements Option<T> {
      //...
      public OptionModule getModule() {
         throw new UnsupportedOperationException();
      }
  }

  final class None implements Option<T> {
      //...
      public OptionModule getModule() {
         throw new UnsupportedOperationException();
      }
  }
}

interface OptionModule {}

OptionModule is not visible outside, so you cannot implement this interface outside this package.

But I think it's possible to implement the same using annotation processing.

@HigherKind(sealed = true)
public interface Option extends OptionOf<T> {

  //..

  final class Some implements SealedOption<T> {
    //...
  }

  final class None implements SealedOption<T> {
      //...
  }
}

The this code will be generated

public interface OptionOf<T> extends Kind<Option_, T> {

  SealedOption<T> youShallNotPass();

  //...
}

// package private
interface SealedOption<T> extends Option<T> {
  @Override
  default SealedOption<T> youShallNotPass() {
    throw new UnsupportedOperationException();
  }
}

This way, if you try to implement Option outside, the compiler will fail, because SealedOption<T> is not visible.

@tonivade tonivade added the enhancement New feature or request label Jun 3, 2020
@tonivade tonivade self-assigned this Jun 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant