As for the strict typed language, I find it strange that Crystal allows to reassign the variable with a different type. I would expect that after the type of the variable was infered from it’s usage, assigning a different type value to that variable in the same scope would produce an error.
This works fine and is concidered a feature of the language:
x = 1
x = "str"
If you explicitly define a type of the variable, you cannot reassign it a different type value (like it’s expected in a strict typed language):
x : Int32
x = 1
x = "str" # Error: type must be Int32, not (Int32 | String)
But that does not work with the method parameters:
def method(x : Int32)
# I would expect this produce an error, but it's not
x = "str"
end
method(0) # "str" : String
Allowing to redefine the variable if the type was infered from the default value could be expected to be consistent with this feature of the language:
def method(x = 0)
x = "str"
end
Summarising:
- Why strict typed language allows to reassign the variable with the different type if the type was infered from the first usage?
- Why it allows to reassign the method parameter with a different type value even it it was explicitly typed in the definition of the method?