Wierd behaviour of parametric type

Hello,

I know this is kind of strange usage of parametric types, but I was wondering what’s going on. Sorry for the imprecise title, since I’m not sure how to describe this question.

Without parametric type, if I define a type and implement a wrong way to use it:

struct Foo
    a::String
    b::Int
end

foo = Foo(1, "hello!")

A method error would trigger since one cannot do the incorrect type conversion, that’s what we expect.

However if I use the parametric type in a wierd way:

struct Foo2{String,Int}
    a::String
    b::Int
end

foo2 = Foo2(1, "hello!")

No error would pop up. Instead, an instance Foo2{Int64,String}(1, "hello!") is generated. The specified type on a and b are violated.

What’s going on here? Any help is appreciated!

In the second example String and Int are not anymore what they mean in the first case, they are just generic parameters. It is the same as:

struct Foo2{A,B}
  a::A
  b::B
end

(of course nobody would ever use that syntax to specify generic types in a parametric type). In other words, Int and String are not reserved keywords, and here they are just assuming another meaning than the most common one. You can also do String = "abc", and that will work.

4 Likes

That totally make sense! Got it, thank you!

1 Like