Today, I was playing with Crystal and saw something interesting, and that could be UX bug. I posted the sample code under the error message. The expected result should be Hello, 10 something; however, compiler complains:
$ crystal run src/lorem.cr
Showing last frame. Use --error-trace for full trace.
In src/lorem.cr:9:17
9 | private def foo() : UInt16
^--
Error: type must be UInt16, not Int32
So, I believe that should be Int32, but the compiler says it should be UInt16 which makes me confused.
require "random"
module Lorem
class Ipsum
def initialize
puts "Hello, #{foo()}"
end
# It's just a way to define a random function
private def foo() : UInt16
Random.new.rand(0..99)
end
end
end
Lorem::Ipsum.new
$ crystal -v
Crystal 0.30.1 [5e6a1b672] (2019-08-12)
LLVM: 4.0.0
Default target: x86_64-unknown-linux-gnu
private def foo() : UInt16
Random.new.rand(0..99)
end
Numbers default to Int32 unless explicitly specified, so your 0..99 would cause #rand to return an Int32 number between 0 and 99. However, you have an UInt16 type restriction on the #foo method. Int32 != UInt16 hence the error.
The way to fix this would be to specify 0..99 as UInt16. I.e. 0_u16..99_u16.
This error message should probably be "method return type is restricted to UInt16, but the method returns Int32 instead" (or something similar) which is a far far less confusing message. Also a very simple PR for someone to make :)
This error message should probably be "method return type is restricted to UInt16, but the method returns Int32 instead" (or something similar) which is a far far less confusing message. Also a very simple PR for someone to make :)
After a few days later playing with Crystal, I believe this will be an attempt to improve UX. I can write the PR if you like, @RX14.
Edit: I fount the related line for this
Most helpful comment
This error message should probably be "method return type is restricted to UInt16, but the method returns Int32 instead" (or something similar) which is a far far less confusing message. Also a very simple PR for someone to make :)