[Question] specifying the type of inputs of Function

I was self-studying about specifying the type of inputs of a function.
I came across with this example.

function Date(y::Int64, m::Int64=1, d::Int64=1)
    err = validargs(Date, y, m, d)
    err === nothing || throw(err)
    return Date(UTD(totaldays(y, m, d)))
end

It works perfectly fine. However, when I tried with my own example:

function test(x::Int8,y::Int8)
    return x+y
end
​
test(1,3)
​
MethodError: no method matching test(::Int64, ::Int64)

Stacktrace:
 [1] top-level scope
   @ In[38]:5
 [2] eval
   @ ./boot.jl:360 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1116

It turns out that there is an error coming from Int8 . However, I don’t get it because 1 and 3 are both integers in the interval of Int8.

1 Like

Int is an abbreviation for the system-word-sized integer. Your literal values are also of this type. Int8 is a distinct smaller type, so your literals do not match that type. In general, avoid specifying types for function argument except for dispatching to different methods.

3 Likes

that’s not how it works:

julia> Int8(8) == Int64(8)
true

julia> Int8(8) === Int64(8)
false

Variables have type, type of a variable is independent of what “value” they carry.

2 Likes

Thank you very much for the answers!

Just to complement previous answers, with your function defined like that, you would need to call it with arguments of type Int8, for example using the default constructor for that type with an appropriate Int64:

julia> typeof(8)
Int64

julia> typeof(Int8(8))
Int8

julia> test(Int8(1),Int8(3))
4
1 Like