If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Tuesday, March 18, 2014

Ceylon: error handling the functional way

/**
Error handling (functional way)
Whenever you call a method which might result in an exception,
in Java you throw an exception which can be caught by the calling method.
But in functional programming there is a tendency to not throw an exception but return it
and make this fact explicit in the return type as well.
In Scala they came up with the Try type which represents a computation that
may result in a value of type A if it is succesful, or in some Throwable if
the computation failed.
In Ceylon there is no need for a Try type, as you can directly use a union type.
**/
shared class NegativeAgeException() extends Exception("Age can never be negative!") {}
shared class Person(shared Integer age) {
shared actual String string => "Person(``age``)";
}
shared object personBuilder extends Basic() {
shared Person | NegativeAgeException build(Integer age) {
return age > 0 then Person(age) else NegativeAgeException();
}
}
/**
main prints
pelssers.demo.NegativeAgeException "Age can never be negative!"
**/
void main() {
Person|NegativeAgeException person = personBuilder.build(-3);
//now we first MUST narrow the union type in order to use it
if (is Person person) {
print("``person`` is valid");
} else if (is NegativeAgeException person) {
print(person);
}
}

No comments:

Post a Comment