Dispatch on type aliases?

Can Julia have dispatch based on type aliases? Something rather similar to Scala 3’s opaque type aliases.

const MyTypeAlias = Float64
a::MyTypeAlias = 78.0 # The compiler should implicitly convert this from Float64 to MyTypeAlias

some_func(a::Float64) = :foo
some_func(a::MyTypeAlias) = :bar
other_func(a::Float64) = :hi

@assert some_func(78.0) == :foo
@assert some_func(a) == :bar
@assert other_func(a) == :hi # MyTypeAlias should be a subtype of Float64

This is rather similar to concrete single inheritance, which I have heard will cause problems for the compiler; But in this case, as the types are the same and we are just changing the dispatch, this should be possible?

PS: I have used Float64 just as an example, please don’t suggest specific workarounds for numeric types.

no. type aliases are just names the compiler doesn’t even know they exist.

I know that this currently doesn’t work, I am asking if adding this has any technical difficulty. It’s a neat feature to have. It should probably use a new keyword like typealias foo = bar if it is to be added.

I think it is very unlikely that we would add it. I know it seems like a reasonable idea, but it doesn’t work. the biggest problem is you would be subtyping concrete types which is really bad (ie would break absolutely everything)

1 Like

Can you elucidate on why this would break the compiler? Since the types are exactly the same, the memory layout shouldn’t be a problem. Will the inlining break? (I am just trying to get a rudimentary sense of why this isn’t possible, not trying to argue that it is.)

What should the following code do?

typealias Int1 = Int
typealias Int2 = Int
x=Int1(1)
y=Int2(1)
x+y

what about

typealias Int3 = Int1
z=Int3(1)
y+z
2 Likes

I don’t see any ambiguity here? The method with the narrowest type matches should be used, which would be sth along the lines of +(x::Int, y::Int) for all three aliases as they don’t define any + methods of their own.

See this issue "hard" type alias or Inheritance from a concrete type · Issue #9821 · JuliaLang/julia · GitHub for discussion about this.

3 Likes