Skip to content
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

Returning Array(Int32) errors if method should return Array(Int32 | String) #7178

Closed
akadusei opened this issue Dec 11, 2018 · 2 comments
Closed

Comments

@akadusei
Copy link

While this works: https://play.crystal-lang.org/#/r/5ro7

def foo(x : Array(Int32 | String))
  typeof(x)
end

# I can pass a Array(Int32) to a method that expects Array(Int32 | String)
puts  foo([1]) #=> Array(Int32)

But this gets a compile error: https://play.crystal-lang.org/#/r/5rmy

def foo : Array(Int32 | String)
  [1]
end

puts foo

Output:

Error in line 5: instantiating 'foo()'

in line 18: type must be Array(Int32 | String), not Array(Int32)

I was kinda hoping returning Array(Int32) from a method that expects a return type of Array(Int32 | String) should pass.

@straight-shoota
Copy link
Member

This is covariance vs contravariance. See #3803 and related issues.

@asterite
Copy link
Member

As @straight-shoota says, it's indeed covariance and contravariance.

Right now there's a bit of inconsistency of what Array(Int32 | String) means depending on when you write it: a type restriction, a return value, the type of an instance variable. No decision has been taken yet.

But yeah, essentially a duplicate of #3803, so closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants