Skip to content

Duta/java-maybe

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

java-maybe

Maybe (some/none) in java.

API

Available in the docs folder, or online here.

Basic usage

Maybe<Integer> three = Maybe.some(3);
// Prints "3"
print(three.isSome() ? three.get() : "None");
// Prints "Some(3)"
print(three);

Maybe<Integer> none = Maybe.none();
// Prints "None"
print(none.isSome() ? none.get() : "None");
// Prints "None"
print(none);

Example function

Non-maybe definition:

public Vec3 add(Vec3 a, Vec3 b) {
    if(a == null) {
        throw new IllegalArgumentException(
            "a cannot be null");
    }
    if(b == null) {
        throw new IllegalArgumentException(
            "b cannot be null");
    }
    return new Vec3(
        a.getX() + b.getX(),
        a.getY() + b.getY(),
        a.getZ() + b.getZ());
}

Maybe definition:

public Maybe<Vec3> add(Maybe<Vec3> a, Maybe<Vec3> b) {
    if(a == null || a.isNone()
    || b == null || b.isNone()) {
        return Maybe.none();
    }
    Vec3 aRaw = a.get();
    Vec3 bRaw = b.get();
    return Maybe.some(new Vec3(
        aRaw.getX() + bRaw.getX(),
        aRaw.getY() + bRaw.getY(),
        aRaw.getZ() + bRaw.getZ()));
}

Non-maybe safe usage:

Vec3 a = ...;
Vec3 b = ...;
Vec3 result;
try {
    result = add(a, b);
} catch(IllegalArgumentException ex) {
    // Take appropriate action
}
System.out.println(result);

Maybe safe usage:

Maybe<Vec3> a = ...;
Maybe<Vec3> b = ...;
Maybe<Vec3> result = add(a, b);
if(result.isNone()) {
    // Take appropriate action
} else {
    System.out.println(result.get());
}

Non-maybe unsafe usage:

Vec3 a = ...;
Vec3 b = ...;
Vec3 result = add(a, b);
System.out.println(result);

Maybe unsafe usage:

Maybe<Vec3> a = ...;
Maybe<Vec3> b = ...;
Maybe<Vec3> result = add(a, b);
System.out.println(result.get());

Querying multiple data sources

When working with methods that return a Maybe:

Maybe<User> user = onlineDB.findUser(name)
    .or(localDB.findUser(name));

When working with methods that do not return a Maybe:

Maybe<User> user = Maybe.perhaps(onlineDB.findUser(name))
    .or(localDB.findUser(name));

Notes

If the compiler can't figure out the type of Maybe you want when doing something like:

Maybe.none()

Write the following instead (replacing String with whatever type you actually want it to be):

Maybe.<String>none()

About

Maybe (some/none) in java

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published