Optional Types in Rogue
I've added built-in optional types to Rogue - classes ending with '?' (e.g. "Integer?") have class definitions automatically generated that are analogous to the following:
class Optional<<$DataType>>
PROPERTIES
value : $DataType
exists : Logical
METHODS
method init
exists = false
method init( value )
exists = true
endClass
Usage of optional types is converted into appropriate usage of that optional type class. For instance, this code:
local i : Integer?
i = 5
i = null
if (i.exists) println i.value
else println "invalid"
is converted into roughly this form internally:
local i : Optional<<Integer>>
i = Optional<<Integer>>( 5 )
i = Optional<<Integer>>()
if (i.exists) println i.value
else println "invalid"
At code generation time, definitions of optional reference types are stripped out since they're unnecessary - reference types can represent "null" without any special mechanism:
local st : String?
st = "Hello"
st = null
if (st.exists) println st.value
else println "invalid"
internally converts to
local st : Optional<<String>>
st = Optional<<String>>( "Hello" )
st = Optional<<String>>()
if (st.exists) println st.value
else println "invalid"
compiles to
local st : String
st = "Hello"
st = null
if (st) println st
else println "invalid"
I've abandoned the idea of doing "null-checked blocks" for reasons that I'll describe in a later post!