Sample Examples
Exemplars are available in the src/example/java directory, a few sample snippets reproduced below:
Conversion
Convert checked Functional Interface instances and Method Handles to unchecked java.util.function.* Functional Interfaces.
Given a method that declares a checked exception (very contrived example):
import java.io.IOException;
class ExceptionalExample {
private static int parse(String text) throws IOException
{
try {
return Integer.parseInt(text);
} catch(NumberFormatException nfe) {
throw new IOException(nfe);
}
}
}
Without Unexceptional, you might write an ugly lambda like so:
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.function.ToIntFunction;
// ...
public void convertFunctional()
{
ToIntFunction<String> a = value -> {
try {
return ExceptionalExample.parse(value);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
a.applyAsInt("42");
}
With Unexceptional, you can just write:
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.function.ToIntFunction;
// ...
public void convertFunctional()
{
ToIntFunction<String> b = Exceptional.uncheckToIntFunction(ExceptionalExample::parse);
a.applyAsInt("42");
}
Invocation
Invoking checked functional types and method handles without wrapping in try-catch.
As an alternative to converting functional types, you can just invoke directly.
Given the contrived parse method from previous example, you can use Unexceptional to invoke directly:
import io.earcam.unexceptional.Exceptional;
// ...
public void invokeFunctional()
{
int fortyTwo = Exceptional.applyAsInt(ExceptionalExample::parse, "42");
}
File List
Contrived example of calling Files::list with Stream API.
Vanilla
// Vanilla Stream API, in a manner that would distress Dijkstra
public static List<String> listFiles(Path path)
{
List<String> a;
try {
a = Files.list(path)
.map(Path::toFile)
.map(t -> {
try {
return t.getCanonicalFile();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
})
.map(File::toURI)
.map(t -> {
try {
return t.toURL();
} catch (MalformedURLException e) {
throw new UncheckedIOException(e);
}
})
.map(Object::toString)
.collect(toList());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return a;
}
Unexceptional / EmeticStream
// Static imports from Exceptional
static List<String> listFiles(Path path)
{
return apply(Files::list, path)
.map(Path::toFile)
.map(uncheckFunction(File::getCanonicalFile))
.map(File::toURI)
.map(uncheckFunction(URI::toURL))
.map(Object::toString)
.collect(toList());
}
// EmeticStream, less efficient on GC, more efficient on the eye
static List<String> listFiles(Path path)
{
return emesis(Files::list, path)
.map(Path::toFile)
.map(File::getCanonicalFile)
.map(File::toURI)
.map(Object::toString)
.collect(toList());
}