Skip to content

Instantly share code, notes, and snippets.

@dsteiner93
Last active January 11, 2018 11:43
Show Gist options
  • Save dsteiner93/4a138f1aebfd6a5f4752 to your computer and use it in GitHub Desktop.
Save dsteiner93/4a138f1aebfd6a5f4752 to your computer and use it in GitHub Desktop.
@def proposal
import lombok.Def;
import java.util.Optional;
import com.google.common.collect.ImmutableMap;
public class DefExample {
public static void main(String[] args) {
System.out.println("All defaults:");
foo(1, 2);
System.out.println();
System.out.println("Overriding a couple defaults:");
foo(1, 2, ImmutableMap.of("d", "not default!", "e", false));
System.out.println();
System.out.println("Passing all parameters:");
Optional<String> g = Optional.of("not default!");
foo(1, 2, 3, "4", false, 5.0, g);
}
private static void foo(int a, int b, @Def("99") int c, @Def("default") String d, @Def("true") boolean e, @Def("99.9") double f,
@Def Optional<String> g) {
System.out.println("a: "+a);
System.out.println("b: "+b);
System.out.println("c: "+c);
System.out.println("d: "+d);
System.out.println("e: "+e);
System.out.println("f: "+f);
System.out.println("g: "+g.orElse("was not passed"));
}
}

When you compile DefExample.java with this fork of lombok in the classpath, it will automatically inject the correct two methods seen below into the same class file.

javac -cp lombok.jar:guava.jar DefExample.java
private static void foo(int a, int b) {
  foo(a, b, 99, "default", true, 99.9, Optional.empty());
}

private static void foo(int a, int b, final java.util.Map<String, Object> paramsMap) {
	foo(a, 
		b, 
		paramsMap.containsKey("c") ? (int)paramsMap.get("c") : 99, 
		paramsMap.containsKey("d") ? (String)paramsMap.get("d") : "default", 
		paramsMap.containsKey("e") ? (boolean)paramsMap.get("e") : true, 
		paramsMap.containsKey("f") ? (double)paramsMap.get("f") : 99.9, 
		paramsMap.containsKey("g") ? (Optional<String>)paramsMap.get("g") : Optional.empty());
}

Now you can run DefExample:

java -cp <path to DefExample.class>:guava.jar DefExample

All defaults:
a: 1
b: 2
c: 99
d: default
e: true
f: 99.9
g: was not passed

Overriding a couple defaults:
a: 1
b: 2
c: 99
d: not default!
e: false
f: 99.9
g: was not passed

Passing all parameters:
a: 1
b: 2
c: 3
d: 4
e: false
f: 5.0
g: not default!

@Def can be used on all primitives (except for char), as well as Strings and Java 8 Optionals. If using Optionals, no default value needs to be provided, as Optional.empty() will automatically be used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment