Lombok.val allows you to
use val as the type of a local variable declaration instead of actually writing the type. When you do this, the type will be inferred from the initializer expression. The local variable will also be made final.
So instead of
final ArrayList<String> example = new ArrayList<String>();
You can write
val example = new ArrayList<String>();
I've tried to do some research into how this actually works but there doesn't seem to be a huge amount of information. Looking at the github page, I can see that val is an annotation type. The annotation type is then used, rather than an actual annotation.
I wasn't even aware you could even use annotation types in this manner but upon testing it the following code is indeed valid. However, I'm still not sure why you would ever want to use the type in this way.
public class Main
{
public @interface Foo { }
public static void main(String... args)
{
Foo bar;
System.out.println("End");
}
}
How does Lombok process these usages if they are not annotations, but annotation types? To my (obviously incorrect) understanding, the syntax should look more like:
@Val foo = new ArrayList<String>();
(I'm aware constraints of annotations mean the above is not valid syntax)
In order for Lombok to work, the source code needs to parse without errors. That's why, as you already mentioned, @val foo = new ArrayList<String>(); wouldn't work.
Although Lombok uses annotations, and an annotation processor, the annotation processor is only used as a means to get involved by the compiler.
Lombok does not have a registered processor for @val. Instead, it processes all java files, visits the whole AST and replaces val by the type of the initialization expression of the local variables.
For the actual replacement, for Eclipse/ecj see this class and this one. For javac, see this class.
Disclosure: I am a Lombok developer.