-
-
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
Typecheck default values if unusued #2636
Comments
Reduced class A
def initialize(@value : Int32 = true)
end
end
a = A.new vs class A
def initialize(@value : Int32 = true)
end
end
a = A.new(1) |
Not sure this is a bug. Right now you can do: # You can only pass a String, but the default value is nil
def foo(value : String = nil)
end
foo # OK
foo "hello" # OK
foo nil # Error In that way you can restrict an argument to a type but use a default value of another type. |
That's just even more inconsistent, isn't it? Whether it errors depending on the type of variable that's restricted. We decided to conflate restriction and declaration for instance variables there, we should keep the rest of the language consistent to it. Also I don't really see a real usecase behind your example tbh. |
I was thinking about having |
IMO it is a bug. It will force to implementor some Maybe there will be a tricky part when the method involves type variables. I was trying some snippets but might reach a separate issue here: https://play.crystal-lang.org/#/r/zbd def foo(o : K, h : Hash(K, V) = { "foo" => "bar" })
h.keys
end
pp foo(7, {1 => 2}) # => [1]
pp foo("sdf") # => ["foo"]
pp foo(8) # => ["foo"] |
Part of this was fixed in #3834 The original title of this issue is "Typecheck default values if unusued", which basically means that this should give a compile error: def foo(x : Int32 = "hello")
end That is, it should give a compile error even if we don't invoke def foo(x = unknown)
end
foo(1) But if we don't pass an argument we get an error. Well, it's the same in Crystal here, and I think that's OK (having to type check all methods even if they are not used will slow down compilation, and I'm not sure it's even possible in all cases) |
This code triggers an expected error
#link 1
but the following snippet compiles and runs just fine contrary to my expectations
#link 2
The text was updated successfully, but these errors were encountered: