4 ms·
> How comes and they don't allow you to optionally provide types in your function/class signatures Perhaps you mean something else, but this is from the book P
by brigandish 6y ago
> How comes and they don't allow you to optionally provide types in your function/class signatures
Perhaps you mean something else, but this is from the book Programming Crystal:
> Returning Values
> A method returns the value of its last expression, so there’s no need to explicitly return that or declare its type. However, if you want to document or directly control that return type, you can explicitly specify the type, as in this example:
> methods_and_procs/methods.cr
def typed_method : Array(Int32)
(42..47).to_a.select { |n| n % 4 == 0 }
end
typed_method # => [44]
- vasilakisfil 6y agoI think it's great that you can declare types optionally, but I think they are allowed for a different reason: documentation and explicitness. I would like Crystal compiler to take into account such definitions and speed up somehow. I know I am talking without experience, I just feel that coming from Ruby to Rust, declaring types on function definitions is not that much of a hassle.
- brigandish 6y agoI don't know if declaring all the types would speed up compilation, but what I do know is that they matter to the code itself. For instance, you can use them to overload methods: # version 1: def add(x : Int, y : Int) x + y end # version 2: def add(x : Number, y : Number) x + y end # version 3: def add(x : Number, y : String) x.to_s + y # convert a number to a string with to_s method end # version 4: def add(x, y) x + y end # new methods: # version 5: def add(x : Number, y : Bool) y ? x : 0 end # version 6: def add(x : String, y : String) if x.to_i? && y.to_i? add x.to_i, y.to_i # calls version 1 else x + y end end add(2, 3) # => 5 add(1.0, 3.14) # => 4.14 add("Hello ", "Crystal") # => "Hello Crystal" add(42, " times") # => "42 times" add 5, true # => 5 add 13, false # => 0 add("12", "13") # => 25 (also from the book) > I just feel that coming from Ruby to Rust, declaring types on function definitions is not that much of a hassle. I'm another one who doesn't understand why declaring types is seen as a hassle, but then I went from C# to Ruby so perhaps I was already used to it. Happy to bring a little back!