Type Systems

Learn to deal with different types of programming languages.

Dealing with different languages

When we refer to something like 42 in code, is that a number, a string, or what? If you have a function like factorial(n), what kind of thing is supposed to go into it, and what’s supposed to come out? The type of elements, functions, and expressions is essential. How a language deals with types is called its type system.

The type system can be an important tool for writing correct programs. For example, in Java, we could write a method like this:

Press + to interact
public long factorial(long n)
{
// ...
}

In this case, both the learner and the compiler can easily deduce that factorial() should take a number and return a number. Java is statically typed because it checks types when code is compiled. Trying to pass in a string simply won’t compile.

We will compare this with Ruby:

Press + to interact
def factorial(n)
# ...
end

What is acceptable input to this method? We can’t tell just by looking at the signature. Ruby is dynamically typed because it waits until runtime to verify types. This gives us tremendous flexibility but it also means that some failures that would be caught at compile time won’t be caught until runtime.

Both static and dynamic approaches to types have their pros and ...