Flow-sensitive typing


In programming language theory, flow-sensitive typing is a type system where the type of an expression depends on its position in the control flow.
In statically typed languages, a type of an expression is determined by the types of the sub-expressions that compose it. However, in flow-sensitive typing, an expression's type may be updated to a more specific type if it follows a statement that validates its type. The type is determined by using type inference and type information is carried using algebraic data types.

Example

Ceylon

See the following example in Ceylon which illustrates the concept:

// Object? means the variable "name" is of type Object or else null
void hello

hello;
hello;
hello;

Which outputs:
Hello, world!
Hello, object 1!
Hello, John Doe!
String.size is 8

Kotlin

See this example in Kotlin:

fun hello

hello

Benefits

This technique coupled with type inference reduces the need for writing type annotations for all variables or to do type casting, like is seen with dynamic languages that use duck typing. It reduces verbosity and makes up for terser code, easier to read and modify.
It can also help language implementers provide implementations that execute dynamic languages faster by predicting the type of objects statically.
Finally, it increases type safety and can prevent problems due to null pointers, labeled by C.A.R. Hoare—the null reference inventor—as "the billion dollar mistake"

Implementations

, created by David J. Pearce, was the first language to make use of flow-sensitive typing in 2009.
Since this introduction, other languages have made use of it, namely Ceylon, Kotlin, TypeScript and Facebook Flow.

External references