I am trying some code snippets with Crystal 1.0.0 and observing this. I am not sure if this is expected behavior, if yes then any detail would be helpful to understand.
Why is 0 not getting typecasted to Float64 only while returning from a function, but assignment & as an argument is being accepted?
1 def func1 ( a : Float64 )
2 # Argument is accepted as Float64
6 def func2 : Float64
7 # Return type as Float64 is not accepted; Compilation error for func2
11 c : Float64 = 0 # Assignment is accepted as Float64
12 puts func1(0)
13 puts func2
6 | def func2 : Float64
Error: method top-level func2 must return Float64 but it is returning Int32
My crystal version - Debian Linux
Crystal 1.0.0 [dd40a2442] (2021-03-22)
Default target: x86_64-unknown-linux-gnu
Because that’s how the language works. It’s easy to see that you pass a number literal to a call. It’s harder to do that when a method can have multiple points where a value is returned.
That said, it might be a nice enhancement. But I’m not sure. It might be misleading if someone reads the code and see an integer being returned, and the return type is far away.
Thanks for the clarification. Coming from C/C++ world, I was expecting same rules for arguments vs return types, that the language would take care of typecasting. Just that I saw that rules seems differently applied in this usecase. May be a consistent behavior would be more logical, just my humble opinion.
“that’s how it works” wasn’t a nice answer. What I really meant is that right now it’s expected behavior :-)
Not an issue
Appreciate your timely responses, very helpful for newbies like me. Thanks for your efforts!