Type annotation in a function specifies a required type for function arguments, a required type for returned data, or a required type for both. If you do not type annotate the parameters of a function, the parameters will be of type Object. Likewise, if the return type for a function is not specified, the compiler will infer the appropriate return type.
Using Type Annotation
Using type annotation for function parameters helps ensure that a function will accept only data that it can process. Declaring a return type explicitly for a function improves code readability, since the type of data that the function will return is immediately clear.
The following example illustrates the use of type annotations for both the parameters and return type of the function.
В | Copy Code |
---|---|
// Declare a function that takes an int and returns a String. function Ordinal(num : int) : String{ switch(num % 10) { case 1: return num + "st"; case 2: return num + "nd"; case 3: return num + "rd"; default: return num + "th"; } } // Test the function. print(Ordinal(42)); print(Ordinal(1)); |
The output of this program is:
В | Copy Code |
---|---|
42nd 1st |
A type mismatch error would be generated if an argument were passed to the Ordinal
function that could not be coerced to an integer. For example, Ordinal(3.14159
) would fail.