Avoid explicit conversion from scientific notation to int for generic struct

Generic structs need an explicit conversion from double to int whereas non-generic don’t. I find this a bit confusing due to the inconsistency. Is there a way to avoid the explicit conversion?

Example:

struct A
    a::Int
end

struct B{T}
    a::T
    b::Int
end

A(1e5) # works
B(3, 1e5) # doesn't work -> Method error: no matching B(::Int64, ::Float64)
B(3, Int(1e5)) # works

I’m usually quite a fan of the fact, that in julia there are fewer rules than in other languages, beacause many things are treated the same. For example that variables and types and functions all just something with a name or that global functions and nested functions and anonymous functions and functions with closures are all just types.

You can add your own constructor:

B(a::T, b::Number) where T = B{T}(a, Int(b))

but it does seem like this could be done automatically. Maybe file an issue?

There’s already an issue for this somewhere. It’s a pretty old one because it’s not entirely clear how to generically generate an outer constructer for a parametric type like this.

4 Likes