What am I missing in these codes?


f1(x::Int)=println("1: $x")
Int(x)=println("int: $x")
f2(x::Int)=println("2: $x")

f2 (generic function with 1 method)


julia> Int(x)=println("int: $x")
Int (generic function with 1 method)

julia> f2(x::Int)=println("2: $x")
ERROR: ArgumentError: invalid type for argument x in method definition for f2 at REPL[2]:1
 [1] top-level scope
   @ REPL[2]:1

Code1 works fine, while Code2 not. It seems like method Int must follow something, which showing Int is a Type, then the intepreter can infer Int is a Type rather than a method?

I’m not sure what causes your specific error, but I’m not surprised you have a bad time redefining the fallback constructor for Int.

Actually hang on. The error mentions f1, which is not in “Code 2”. Is anything left out?

Execuse me, it is a copy mistake, I have rewrited it.

By defining Int(x) (before every using/accessing the type Int) you are overshadowing what Int usually refers to (namely Core.Int). After you definition Int isn’t the standard integer datatype anymore but your function. And you can’t use x::Int the the function signature of f2 because that’s essentially x::some_function which isn’t valid.


julia> Int

julia> typeof(Int)

to (in a fresh session)

julia> Int(x) = println("int: $x")
Int (generic function with 1 method)

julia> Int
Int (generic function with 1 method)

julia> typeof(Int)
typeof(Int) (singleton type of function Int, subtype of Function)

(Note that you could, in principle, do f2(x::Core.Int) = ...)

Most importantly, though, you shouldn’t do this anyways. Int(x) already has a meaning and it’s not to print something.