Julia automatically converts datatype in function call

I have a function that takes Int32 values as input.

function overlap(alpha1::Float64, l1::Int32, m1::Int32, n1::Int32, a::Vector{Float64},
    alpha2::Float64, l2::Int32, m2::Int32, n2::Int32, b::Vector{Float64})
    ---implementation ---
    return value;
end

Now I want to calculate for a set of variables:
overlap(gto1.alpha, gto1.l, gto1.m, gto1.n, gto1.r, gto2.alpha, gto2.l+2, gto2.m, gto2.n, gto2.r)
However, the value with addition return a Int64 and therefore causes an error. I have to do:
overlap(gto1.alpha, gto1.l, gto1.m, gto1.n, gto1.r, gto2.alpha, Int32(gto2.l+2), gto2.m, gto2.n, gto2.r)
For it to work correctly. Is there a way to make Julia not convert the datatypes when it operates on them like this? I am doing this kind of correction many times in my code.

What exactly are you doing? Adding two Int32 gives an Int32:

julia> Int32(1) + Int32(2)
3

julia> typeof(Int32(1) + Int32(2))
Int32

Is the problem that you’re using literals that have type Int64 like 2?

1 Like

The general solution is to not use such tight type annotations. It’s rare that you actually need to restrict a particular implementation to only accepting ::Int32s unless you’re doing really low-level bit banging. Simply using ::Integer would work just as well. Heck, I’d probably not worry about any types in your method definition at all.

Julia’s performance does not change with the addition or removal of type annotations on a method’s definition.

3 Likes

use this function signature

function overlap(a::T, b::T) where {T<:Int32} .... end
to make sure both arguments are Int32 and then it will satisfy closure property.

Yes the problem was the +2.

It is nice to know that.

It doesnt solve the addition conversion problem when the function is called but it’s definitely easier to declare this way.

I wouldn’t call it a “conversion problem” since 2 is an Int64 and the most sensible thing when adding an Int32 and Int64 is to return an Int64. I think there have been discussions elsewhere in this forum about making numeric literals default to a different type. But as noted above, the best solution is to not be so restrictive on your arguments.

1 Like

+2 by default is int64. you should use gto2.l+Int32(2)

you should better pass the structure into the function:
function overlap(gto1::MyStructure, gto2::MyStructure, l::Int32)
…
end

2 Likes