diff --git a/src/array.jl b/src/array.jl index f9a015e9..e1128305 100644 --- a/src/array.jl +++ b/src/array.jl @@ -480,7 +480,8 @@ similar(A::CategoricalArray{S, M, Q}, ::Type{Union{CategoricalValue{T}, Missing} dims::NTuple{N, Int}) where {T, N, S, M, Q} = CategoricalArray{Union{T, Missing}, N, Q}(undef, dims) -for A in (:Array, :Vector, :Matrix) # to fix ambiguities +# AbstractRange methods are needed since collect uses 1:1 as dummy array +for A in (:Array, :Vector, :Matrix, :AbstractRange) @eval begin similar(A::$A, ::Type{CategoricalValue{T, R}}, dims::NTuple{N, Int}=size(A)) where {T, R, N} = @@ -780,7 +781,7 @@ function in(x::CategoricalValue, y::CategoricalArray{T, N, R}) where {T, N, R} end Array(A::CategoricalArray{T}) where {T} = Array{T}(A) -collect(A::CategoricalArray{T}) where {T} = Array{T}(A) +collect(A::CategoricalArray) = copy(A) function float(A::CategoricalArray{T}) where T if !isconcretetype(T) diff --git a/test/13_arraycommon.jl b/test/13_arraycommon.jl index 771b608c..98402de4 100644 --- a/test/13_arraycommon.jl +++ b/test/13_arraycommon.jl @@ -222,6 +222,14 @@ end y = similar(Vector{T}, (3,)) @test isa(y, Vector{T}) @test size(y) == (3,) + + y = similar(1:1, Union{CategoricalValue{String, UInt8}, T}) + @test isa(y, CategoricalVector{Union{String, T}, UInt8}) + @test size(y) == (1,) + + y = similar(1:1, Union{CategoricalValue{String, UInt8}, T}, (3,)) + @test isa(y, CategoricalVector{Union{String, T}, UInt8}) + @test size(y) == (3,) end @testset "copy" begin @@ -1145,18 +1153,20 @@ end end end -@testset "collect of CategoricalArray produces Array" begin +@testset "collect of CategoricalArray produces CategoricalArray" begin x = [1,1,2,2] y = categorical(x) - z = collect(y) - @test typeof(x) == typeof(z) - @test z == x + for z in (collect(y), collect(eltype(y), y), collect(Iterators.take(y, 4))) + @test typeof(y) == typeof(z) + @test z == y == x + end x = [1,1,2,missing] y = categorical(x) - z = collect(y) - @test typeof(x) == typeof(z) - @test z ≅ x + for z in (collect(y), collect(eltype(y), y), collect(Iterators.take(y, 4))) + @test typeof(y) == typeof(z) + @test z ≅ y ≅ x + end end @testset "Array(::CategoricalArray{T}) produces Array{T}" begin