Skip to content

Commit 2390055

Browse files
authored
Merge pull request #17968 from JuliaLang/teh/similar_for
Provide a better error for `similar` methods with Dict
2 parents 7199111 + eb95919 commit 2390055

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

base/dict.jl

+3
Original file line numberDiff line numberDiff line change
@@ -848,3 +848,6 @@ function similar(t::ImmutableDict)
848848
end
849849
return t
850850
end
851+
852+
_similar_for{P<:Pair}(c::Dict, ::Type{P}, itr, isz) = similar(c, P)
853+
_similar_for(c::Associative, T, itr, isz) = throw(ArgumentError("for Associatives, similar requires an element type of Pair;\n if calling map, consider a comprehension instead"))

test/dict.jl

+5
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,11 @@ d = Dict('a'=>1, 'b'=>1, 'c'=> 3)
388388
@test [d[k] for k in keys(d)] == [d[k] for k in eachindex(d)] ==
389389
[v for (k, v) in d] == [d[x[1]] for (i, x) in enumerate(d)]
390390

391+
# generators, similar
392+
d = Dict(:a=>"a")
393+
@test @inferred(map(identity, d)) == d
394+
@test @inferred(map(p->p.first=>p.second[1], d)) == Dict(:a=>'a')
395+
@test_throws ArgumentError map(p->p.second, d)
391396

392397
# Issue 12451
393398
@test_throws ArgumentError Dict(0)

0 commit comments

Comments
 (0)