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

No overload matches with subtype #2532

Closed
teodor-pripoae opened this issue Apr 29, 2016 · 1 comment
Closed

No overload matches with subtype #2532

teodor-pripoae opened this issue Apr 29, 2016 · 1 comment

Comments

@teodor-pripoae
Copy link

Hi

I have the following code:

require "json"

def test_method(ids : Array(String), options : Hash(String, JSON::Type))
  options.merge({"ids": ids})
end

puts test_method(["123", "456"], {"asdf": "foo", "data": {"a": "b"}})

Since Hash(String, Hash(String, String) | String) is a subtype permitted by JSON::Type, it should work.

I'm getting this error:

Error in ./test.cr:7: no overload matches 'test_method' with types Array(String), Hash(String, Hash(String, String) | String)
Overloads are:
 - test_method(ids : Array(String), options : Hash(String, JSON::Type))

puts test_method(["123", "456"], {"asdf": "foo", "data": {"a": "b"}})
@asterite
Copy link
Member

The answer is: it depends.

Consider this:

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

a = Array(Int32).new
foo(a)

Should it compile? Well, if we only read from x then the answer is yes. If we write to x then probably no (we wouldn't want to insert a string inside an array of ints).

There's a tracking issue for covariance and contravariance, #1297. I'll close this in favor of that one. Until we resolve what to do with this no sane behaviour can be expected from this. Your best option right now is to either don't use a type annotation, or type the hash as the property type:

require "json"

def test_method(ids, options)
  options.merge({"ids": ids})
end

puts test_method(["123", "456"], {"asdf": "foo", "data": {"a": "b"}})
require "json"

def test_method(ids : Array(JSON::Type), options : Hash(String, JSON::Type))
  options.merge({"ids": ids} of String => JSON::Type)
end

puts test_method(
  ["123", "456"] of JSON::Type,
  {
    "asdf": "foo" as JSON::Type,
    "data": {"a": "b"} of String => JSON::Type,
  } of String => JSON::Type)

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

No branches or pull requests

2 participants