Skip to content

Commit 1470fc0

Browse files
committed
Add convert to Option from Option
1 parent 03b9323 commit 1470fc0

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/ErrorTypes.jl

+27
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
# Note: This module is full of code like:
2+
# if x.data isa Thing
3+
# x.data._1
4+
# else
5+
#
6+
# this is so the compiler won't typecheck inside the if blocks.
7+
# that in turns leads to more effective code.
8+
9+
110
module ErrorTypes
211

312
using SumTypes
@@ -102,6 +111,24 @@ None
102111
const none = None{Nothing}().data
103112
Base.convert(::Type{<:Option{T}}, ::None{Nothing}) where T = None{T}()
104113

114+
function Base.convert(::Type{Option{T1}}, x::Option{T2}) where {T1, T2 <: T1}
115+
data = x.data
116+
if data isa Thing
117+
Thing{T1}(data._1)
118+
else
119+
None{T1}()
120+
end
121+
end
122+
123+
function Base.convert(::Type{Option{T1}}, x::Option{T2}) where {T1, T2}
124+
data = x.data
125+
if data isa None
126+
return None{T1}()
127+
else
128+
error("cannot convert Thing value")
129+
end
130+
end
131+
105132
"""
106133
Thing(x::T)
107134

test/runtests.jl

+8-2
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,19 @@ using Test
88
@test !(None{Float32}() isa Option{AbstractFloat})
99
@test !(None{Int}() isa None)
1010

11-
# Conversion
11+
# Conversion from none
1212
@test convert(Option{Int}, none) isa Option{Int}
1313
@test convert(Option{Some{Nothing}}, none) isa Option{Some{Nothing}}
14-
1514
@test_throws MethodError convert(Int, none)
1615
@test_throws MethodError convert(Option{String}, "foo")
1716

17+
# Convert from Option
18+
@test convert(Option{Integer}, Thing(1)) isa Option{Integer}
19+
@test convert(Option{Union{String, Dict}}, Thing("foo")) isa Option{Union{String, Dict}}
20+
@test convert(Option{String}, None{Int}()) isa Option{String}
21+
@test convert(Option{Float64}, None{Float64}()) isa Option{Float64}
22+
@test_throws ErrorException convert(Option{String}, Thing(1))
23+
1824
# is_none
1925
@test is_none(None{Int}())
2026
@test is_none(convert(Option{String}, none))

0 commit comments

Comments
 (0)