Ceylon (programming language): Difference between revisions

Content deleted Content added
No edit summary
m Language features: <source lang="java">
Line 54:
More uniquely, Ceylon allows for union and intersection types, where a variable can have more than one type. For example, here is a Ceylon function which may take either an [[Integer (computer science)|integer]] or a [[String (computer science)|string]]:
 
<source lang="java">
<pre>shared void integerOrString(Integer|String input) {
if (is Integer input) {
print("Got the integer ``input``");
Line 61 ⟶ 62:
}
}
</presource>
 
An important component of this feature is flow-based typing. For example, the following code is invalid:
 
<source lang="java">
<pre>shared void integerOrString(Integer|String input) {
Integer added = input + 6; // Illegal, we don't know that input is definitely an integer.
 
Line 75 ⟶ 77:
}
}
</presource>
 
The first example is wrong because the <code>+</code> operator is not defined for <code>Integer|String</code>, only for <code>Integer</code>, but, within the if block, we have checked the type of <code>input</code> and know it to be simply an <code>Integer</code>, so Ceylon ''narrows'' the type of the variable <code>input</code> and we can treat it like an integer.