-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
type inference weirdness #9184
Comments
I read the entry about variance and covariance in the handbook. It says the type of the array needs to be set explicitly. However, in my case the type of the input splat is defined as |
So what's happening is that you're effectively passing an Anyways, for now you can do |
@jhass Thanks for the the explanation, it makes sense. At least in a "now I understand what's happening" way. Shall I keep the issue open? |
I'm not sure, let's see what others think. It is indeed not very actionable and mostly covered by #3803 and all the related issues we already have open I think. |
I don't think this can be changed in a fundamental way. Maybe when we get to revisit generics and improve covariance. |
Additionally, if the inconsistency can not be resolved easily, perhaps a warning could be printed if someone attempts something similar? That way at least I would see the same thing on the console regardless of what parameters I pass into the splat (instead of compilation error in one case and works fine in the other) |
|
I suppose module Enumerable
def to_a(type : U.class = T) forall U
ary = [] of U
each { |e| ary << e }
ary
end
end
class Foo
end
class Bar < Foo
end
class Baz < Foo
end
typeof([Bar.new, Bar.new].to_a(Foo)) # => Array(Foo)
typeof([Bar.new, Bar.new].to_a) # => Array(Bar) |
On master there is a different way to convert any abstract class Animal; end
class Dog < Animal; end
class Cat < Animal; end
class House
@animals : Array(Animal)
def initialize(*animals : Animal)
@animals = [*animals] of Animal
end
end
House.new(Cat.new, Cat.new) # => #<House:... @animals=[#<Cat:...>, #<Cat:...>]> Similarly However, if the argument is additionally an Array(Animal).new(animals.size) do |i|
animals.unsafe_fetch(i)
end For some reason Crystal itself doesn't seem to use that outside |
Sorry for the very generic issue title, I've bumped into this rather confusing situation, and I have no idea what causes it so I couldn't really come up with a better one. Let the snippets do the talking:
If I change one of the cats into a
Dog
, it compiles.The text was updated successfully, but these errors were encountered: