Core.Value - Year4000/Utilities GitHub Wiki
The value system is like the Optional class except it contains more methods. View the Javadocs to read more about it.
The reason to use an Interface instead of a class is the ability to have sub classes that contains the same structure as Value. There are some differences that make Value more powerful in our option. One of the additions is parsing of Numbers from strings. Another change that was made is chaining multiple actions in one line.
Note - Empty Strings are treated like null values
// Creates an empty value
Value.empty();
// Special handling for Strings, empty strings are treated like null values
Value.of("");
// Creates a value wrapper of the Optional containing value
Value.of(Optional.of("Some Value"));
// Creates a value wrapper of the Value containing value
Value.of(Value.of("Some Value"));
// Standard way of creating value instances
Value.of(new Object());
There are multiple ways to create the Value instance.
Note - Value.get()
does not throw a NullPointerException it just returns null.
Value<String> value = Value.of("Hello World");
// Get the value that is within
V = value.get();
// Get the value that is within
V = value.getOrElse("Other");
// Gets the value of this instance or throw NullPointerException
V = value.getOrThrow();
// Gets the value of this instance or throw NullPointerException with the provided message.
V = value.getOrThrow("Oh know the value is empty!!!");
One of the big benefits that Value has is the ability to parse Number values from Strings with out having a huge block of code to deal with exceptions.
Value<Boolean> value = Value.parseBoolean("true");
Value<Byte> value = Value.parseByte("1");
Value<Double> value = Value.parseDouble("3.14");
Value<Float> value = Value.parseFloat("2.17");
Value<Integer> value = Value.parseInteger("4000");
Value<Long> value = Value.parseLong("3000000");
Value<Short> value = Value.parseShort("1234");
Chaining multiple methods together with the combine features make you allow to do validation in one simple line.
// Some method that returns a username if its not found default to `unknown`
String username = Value.of(someMethod()).getOrElse("unknown");
// Some method that can return a password, then hashes the password if its found otherwise throw an Exception
String password = Value.of(someOtherMethod())
.ifPresent(password -> Hashs.hash(password))
.getOrThrow("Password not found");