*Edit: changed title to be more accurate
Hi, everyone. So, I`m not exactly new to julia but this feels like it belongs here as it is quite basic and still puzzles me.
Let’s consider the MWE in following code snippet:
struct B
x::Ref{Union{Nothing,Int}}
y::Int
end
struct B2{T}
x::Ref{Union{Nothing,Int}}
y::T
end
So far, so good. Both structs only differ in the fact that B2
is a parametric type for the second variable, y
. Here comes the bit that confused me:
b = B(nothing,1)# works, returns B(Base.RefValue{Union{Nothing, Int64}}(nothing), 1)
b2 = B2(nothing,1)# ERROR: MethodError: no method matching B2(::Nothing, ::Int64)
b2 = B2(convert(Ref{Union{Nothing,Int}},nothing),1) #works, returns B2{Int64}(Base.RefValue{Union{Nothing, Int64}}(nothing), 1)
b2 = B2{Int}(nothing, 1) #works, returns B2{Int64}(Base.RefValue{Union{Nothing, Int64}}(nothing), 1)
In the first line, julia seems to realize that I want b
to hold a Ref to nothing. This seems to be because nothing
can apparently be converted to the type Ref{Union{Nothing,Int}}
(somewhat surprising).
However, if I consider the parametric type B2
, this automatic conversion no longer works (line 2). This surprises me even more, because the type T
has nothing to do with x
.
This can be cirumvented by either converting nothing
explicitly, or providing the type T
directly.
- But why does julia not do again what it did in the first example and convert this automagically?
- Anyway, is this rather unintuitive type conversion something that one can rely on, or could it be that it is unintended behaviour and might change in future minor releases?
Thanks for your insight!