Why `get(d, k, default)` allows `default` of a type different than `valtype(d)`?

I don’t understand why get(d, k, default) allows default to be of a type different than valtype(d). This violates type-stability, and it has been a source of may bugs for me. I have heard an argument that sometimes people return something else to signal that the key was not found. But isn’t that what haskey is for?

Julia is a dynamic language, so it doesn’t generally enforce type stability. Notably, using nothing as a default can be useful in some cases. I agree sometimes it would be nice to have get call convert(valtype(d), default), but that would be less flexible/general. Note that calling haskey first and then get/getindex requires looking up the key twice, which has a performance impact.

2 Likes