Hacker News new | ask | show | jobs
by vasilakisfil 1909 days ago
I 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.

1 comments

I 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!