For example, adding a (previously undeclared) int and a string in pseudocode:
x = 1;
y = "2";
x + y = z;
I've seen strongly typed languages that would not allow adding the two types, but those are also statically typed, so it's impossible to have a situation like above. On the other hand, I've seen weakly typed languages that allow the above and are statically typed.
Are there any languages that are dynamically typed but are also strongly typed as well, so that the piece of code above would not be valid?
Sure: Python.
>>> a = 3
>>> b = "2"
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> b = 2
>>> a+b
5
Ruby is dynamically typed, but strongly typed.
irb(main):001:0> 2 + "3"
TypeError: String can't be coerced into Fixnum
from (irb):1:in `+'
from (irb):1
irb(main):002:0> "3" + 2
TypeError: can't convert Fixnum into String
from (irb):2:in `+'
from (irb):2
irb(main):003:0> "3" + 2.to_s
=> "32"
irb(main):004:0> 2 + "3".to_i
=> 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With