Strong Typing vs Weak Typing

Large stone monument in a field with some red wildflowers with little stone buddy

Last time, we talked about static and dynamic typing, and the differences between the two.

To start off, I do have some bad news to share with you. There is no specific definition of what is strongly typed and what is weakly typed. It's more of a range. A spectrum. A dial.

However, what we WILL do is discuss the characteristics of each so that even if we can't precisely say beyond the shadow of a doubt that a language is strongly typed or weakly typed, we can compare two different languages and say which may be more strongly typed than the other.

I like to think of whether or not a language is strongly typed or not is based around just how a single data type in it plays well with other data types.

Let's look at Ruby.

"abc" + 123

Here, we are adding a string, "abc" to an integer, 123. Ruby will indeed yell at you if you attempt to do this. It will give you this error message:

TypeError: no implicit conversion of Integer to String

And that's the crux of the difference between strong typing and weak typing. In strongly typed languages, we will not have an implicit conversion from one data type to another data type. In this particular example, Ruby will not go ahead and convert the integer into a string and vice versa to make this work.

If we would want to make this work, we would have to do some specific and explicit type conversions in order to get this operation to work. For example, something like this:

"abc" + 123.to_s

Here, we are explicitly converting the integer into a string before concatenating it with "abc".

We talk a lot here about what it means to be strongly typed, so let's look at it in JavaScript.

data = 5
thing = $data+"string"

What this does is that it will concatenate the two values, even though they are of different types and we will get the value "5string" stored in the thing variable.

What we have heres is an IMPLICIT data type conversion from an integer to a string so that it can then be concatenated with the second string. Weakly typed.

Subscribe to Rust for Rubyists

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.