Property definitions

core $ MaybeError :: defaultinit
# 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