Search code examples
juliatypechecking

julialang: can (should) this type error be caught at compile time?


function somefun()
    x::Int = 1
    x = 0.5
end

this compiles with no warning. of course calling it produces an InexactError: Int64(0.5). question: can you enforce a compile time check?


Solution

  • Julia is a dynamic language in this sense. So, no, it appears you cannot detect if the result of an assignment will result in such an error without running the function first, as this kind of type checking is done at runtime.

    I wasn't sure myself, so I wrapped this function in a module to force (pre)compilation in the absence of running the function, and the result was that no error was thrown, which confirms this idea. (see here if you want to see what I mean by this).

    Having said this, to answer the spirit of your question: is there a way to avoid such obscure runtime errors from creeping up in unexpected ways?

    Yes there is. Consider the following two, almost equivalent functions:

    function fun1(x     ); y::Int = x; return y; end;
    function fun2(x::Int); y::Int = x; return y; end;
    
    fun1(0.5)   # ERROR: InexactError: Int64(0.5)
    fun2(0.5)   # ERROR: MethodError: no method matching fun2(::Float64)
    

    You may think, big deal, we exchanged one error for another. But this is not the case. In the first instance, you don't know that your input will cause a problem until the point where it gets used in the function. Whereas in the second case, you are effectively enforcing a type check at the point of calling the function.

    This is a trivial example of programming "by contract", by making use of Julia's elegant type-checking system. See Design By Contract for details.

    So the answer to your question is, yes, if you rethink your design and follow good programming practices, such that this kind of errors are caught early on, then you can avoid having them occuring later on in obscure scenarios where they are hard to fix or detect.

    The Julia manual provides a style guide which may also be of help (the example I give above is right at the top!).