Crystal: types conflict when using generic modules with same parameter name

Created on 31 Mar 2017  路  6Comments  路  Source: crystal-lang/crystal

https://carc.in/#/r/1skn

module Foo(T)
  @x = T.new
end

module Bar(T)
  @y = T.new
end

class A
  include Foo(Int32)
  include Bar(String)
end

causes error message:
Error in line 2: instance variable '@x' of A must be Int32, not String

this don't reproduce when using methods def foo : T or even @x : T, only with = T.new

bug compiler

Most helpful comment

@ozra right now i'm using macros instead of modules for this, so it's not critical, but modules will make code slightly cleaner and typesafer.

All 6 comments

That's expected behaviour. What would you expect the compiler to do? Or put another way, what use case does this prevent?

@asterite I can't spot the error in this. There's 2 different instance variables coming from 2 different modules with generic types, and somehow there's a type error? To my untrained eye, it would seem the T in T.new is of incorrect type.

@asterite I want to include one module that declare property x and another module that declare property y, so the class will have @x : Int32 and @y : String.

Maybe i should have used more visually different names for them, sorry if that confused you.

@konovod Oh! I though they had the same name @x. I see the error now, hmm...

@konovod - good catch! This is not something I would have ever thought of using (_so far_) and still it's so straight forward!

And I guess there's a reason for foo, bar, ... X-D

@ozra right now i'm using macros instead of modules for this, so it's not critical, but modules will make code slightly cleaner and typesafer.

Was this page helpful?
0 / 5 - 0 ratings