core :: MaybeError
Functions that return useful values or errors could use it to simulate an easy-to use multiple-return.
fun division(a,b: Int): MaybeError[Int, Error]
do
if b == 0 then return new MaybeError[Int, Error](null, new Error("Arithmetic Error: try to divide {a} by 0"))
return new MaybeError[Int, Error](a / b, null)
end
assert division(10, 2).is_error == false
assert division(10, 0).is_error == true
Clients has to handle the error:
var res = division(10, 2)
if res.is_error then
print res.error
exit 1
end
print res.value
assert res.value == 5
core :: MaybeError :: defaultinit
core :: MaybeError :: maybe_error=
The error, if anycore :: MaybeError :: maybe_value=
The value, if anycore $ MaybeError :: SELF
Type of this instance, automatically specialized in every classcore :: Object :: class_factory
Implementation used byget_class
to create the specific class.
core :: MaybeError :: defaultinit
core :: Object :: defaultinit
core :: Object :: is_same_instance
Return true ifself
and other
are the same instance (i.e. same identity).
core :: Object :: is_same_serialized
Isself
the same as other
in a serialization context?
core :: Object :: is_same_type
Return true ifself
and other
have the same dynamic type.
core :: MaybeError :: maybe_error=
The error, if anycore :: MaybeError :: maybe_value=
The value, if anycore :: Object :: output_class_name
Display class name on stdout (debug only).
# Helper class used as a return value of methods that may give errors instead of values.
#
# Functions that return useful values or errors could use it to simulate an easy-to use multiple-return.
#
# ~~~
# fun division(a,b: Int): MaybeError[Int, Error]
# do
# if b == 0 then return new MaybeError[Int, Error](null, new Error("Arithmetic Error: try to divide {a} by 0"))
# return new MaybeError[Int, Error](a / b, null)
# end
#
# assert division(10, 2).is_error == false
# assert division(10, 0).is_error == true
# ~~~
#
# Clients has to handle the error:
#
# ~~~
# var res = division(10, 2)
# if res.is_error then
# print res.error
# exit 1
# end
# print res.value
# assert res.value == 5
# ~~~
class MaybeError[V, E: Error]
# The value, if any
var maybe_value: nullable V
# The error, if any
var maybe_error: nullable E
# It there an error?
fun is_error: Bool do return maybe_error != null
# The value
# REQUIRE: `not is_error`
fun value: V do return maybe_value.as(V)
# The error
# REQUIRE: `is_error`
fun error: E do return maybe_error.as(E)
redef fun to_s do
var e = maybe_error
if e != null then return e.to_s
return value.as(not null).to_s
end
end
lib/core/error.nit:42,1--91,3