This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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