4 ms·
On local variables (http://crystal-lang.org/docs/syntax_and_semantics/local_variables.html http://crystal-lang.org/docs/syntax_and_semantics/local_vari...) the
by anilgulecha 11y ago
On local variables (http://crystal-lang.org/docs/syntax_and_semantics/local_variables.html http://crystal-lang.org/docs/syntax_and_semantics/local_vari...) the page says the internal type changes, when a value of a different type is assigned to a variable.
Doesn't this defeat a large advantage that static typing has over dynamic typing -- catching when something is set incorrectly?
- asterite 11y agoNot quite. The language allows you to program using duck-typing, in a way. For example if you have a variable "duck" and you assign a Duck to it and invoke "quack" on it, given a Duck quacks, it will work. Now if later you assign a Horse to it, and the horse doesn't quack, you will get a compile error. So, the compiler catches the error at compile time. Now, if you assign another type, say, a Goose, and it quacks, then the code continue to compile fine (provided that it returns the correct type, which again is determined by its methods, and so on). The new type will be Duck | Goose. In short: there's no "undefined method" errors at runtime in Crystal, so you have the same guarantees that a statically type checked language gives you, plus the ability to program in a duck-type oriented way.