Flow-sensitive typing: Difference between revisions

Content deleted Content added
Add "pattern matching" as an alternative to flow-sensitive typing
No edit summary
Line 86:
[[Pattern matching]] reaches the same goals as flow-sensitive typing, namely reducing [[verbosity]] and making up for terser code, easier to read and modify.
It achieves this is in a different way, it allows to match the type of a structure, extract data out of it at the same time by declaring new variable. As such, it reduces the ceremony around type casting and value extraction. Pattern matching works best when used in conjunction with [[algebraic data types]] because all the cases can be enumerated and statically checked by the compiler.
 
See this example mock for future Java versions <ref>{{cite web |title=Pattern Matching for Java |url=https://cr.openjdk.java.net/~briangoetz/amber/pattern-match.html|website=openjdk.java.net |language=en-us |date=September 2018 |accessdate=1 October 2021 |author=Gavin Bierman and Brian Goetz}}</ref>:
<syntaxhighlight lang="java">
int eval(Node n) {
return switch(n) {
// try to type cast "Node" into "IntNode", and create the variable "i" of type "int".
// If that works, then return the value of "i"
case IntNode(int i) -> i;
// try to type cast "Node" into "NegNode", and create the variable "n" of type "Node".
// If that works, then return the negation of evaluating the "n" node
case NegNode(Node n) -> -eval(n);
// try to type cast "Node" into "AddNode", and create the variables "left" and "right" of type "Node".
// If that works, then return the addition of evaluating the "left" and "right" nodes
case AddNode(Node left, Node right) -> eval(left) + eval(right);
// try to type cast "Node" into "MulNode", and create the variables "left" and "right" of type "Node".
// If that works, then return the multiplication of evaluating the "left" and "right" nodes
case MulNode(Node left, Node right) -> eval(left) * eval(right);
// no "default" because the compiler knows all the possible cases have been enumerated
};
}
</syntaxhighlight>
 
In a statically typed language, the advantage of pattern matching over flow-sensitive typing is that the type of a variable always stays the same: it does not change depending on control flow. When writing down the pattern to be matched, a new variable is declared that will have the new type.