1

Let's pretend that I hated null. Let's pretend that making it opt-out, like @Nullable, doesn't go far enough for me. Let's say I wanted it to be opt in; if an object is not explicitly annotated with @Nullable, then nulls are not allowed.

Example:

MyClass derp = null;           // Compiler error
@Nullable MyClass derp = null; // Fine
@Nullable Integer x = 4;       // Fine
@Nullable Integer x = null;    // Fine
Integer x = 4;                 // Fine
Integer x = null;              // Compiler error

Another example:

public static void myFunction(@Nullable Integer x) {
    Integer y = x;   // Compiler error, because we know x might
                     // be null, and that's not allowed. In other
                     // words: Integer != @Nullable Integer
}

How would I go about this? Would I write some sort of javac plugin? Perhaps a pre-compiler-pass? Maybe there's a framework out there that does this? Or perhaps I could modify the source code of javac?

Thanks!

Verdagon
  • 2,456
  • 3
  • 22
  • 36
  • What do you plan to do about arrays? I would try to think through all the language changes you'd need before you consider implementation. – Jon Skeet Aug 29 '13 at 06:08
  • Huh... good point. Perhaps I'd make it call the default constructor, or just outlaw things like MyClass[] in favor of Nullable[]. I'm not saying that we *should* do what my question proposes, but I'd like to know just how hard it would be if we did decide to do it. – Verdagon Aug 29 '13 at 06:21
  • 1
    Well the difficulty level is going to depend on how much of the language is changed, isn't it? At least to a large extent. – Jon Skeet Aug 29 '13 at 06:23
  • Perhaps. The problem is bounded in the realm of static analysis, so it shouldn't be monumentally difficult... people have written stuff like this before, right? – Verdagon Aug 30 '13 at 03:13
  • There are languages which disallow nulls, yes. But it's tricky, and trying to work out how you'll do it without first deciding what you're going to do seems like a bad idea to me. The precise details could easily change the feasibility of a particular approach. – Jon Skeet Aug 30 '13 at 05:43

1 Answers1

0

Within code areas marked with @NonNullByDefault you basically get what the question asks for: any exception from that default needs to be explicitly declared. The default can be declared per class/interface or per package.

Note 1: You want the Java-8 variant of null annotations (null type annotations), so they affect type references in all positions.

Note 2: See the Java doc for details, where exactly the default applies (which can be fine tuned, btw). ARRAY_CONTENTS is intentionally omitted from this, due to difficulties like those mentioned in @Jon Skeet's comment.

Stephan Herrmann
  • 7,963
  • 2
  • 27
  • 38