1.. 2 Copyright (c) 2021-2024 Huawei Device Co., Ltd. 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 http://www.apache.org/licenses/LICENSE-2.0 7 Unless required by applicable law or agreed to in writing, software 8 distributed under the License is distributed on an "AS IS" BASIS, 9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 See the License for the specific language governing permissions and 11 limitations under the License. 12 13.. _Experimental Features: 14 15Experimental Features 16##################### 17 18.. meta: 19 frontend_status: Partly 20 21This Chapter introduces the |LANG| features that are considered a part of 22the language, but have no counterpart in |TS|, and are therefore not 23recommended to those who need a single source code for |TS| and |LANG|. 24 25Some features introduced in this Chapter are still under discussion. They can 26be removed from the final version of the |LANG| specification. Once a feature 27introduced in this Chapter is approved and/or implemented, the corresponding 28section will be moved appropriately to the body of the specification. 29 30The *array creation* feature introduced in :ref:`Array Creation Expressions` 31enables users to dynamically create objects of array types by using runtime 32expressions that provide the array size. This is a useful addition to other 33array-related features of the language, such as array literals. 34 35The construct can also be used to create multi-dimensional arrays. 36 37The feature *function and method overloading* is supported in many 38(if not all) modern programming languages. Overloading functions/methods 39is a practical and convenient way to write program actions that are similar 40in logic but different in implementation. 41 42.. index:: 43 implementation 44 array creation 45 runtime expression 46 array 47 array literal 48 construct 49 function overloading 50 method overloading 51 52The |LANG| language supports (as an experimental feature at the moment) two 53semantically and syntactically different implementations of overloading: the 54|TS|-like implementation, and that of other languages. See 55:ref:`Function and Method Overloading` for more details. 56 57Section :ref:`Native Functions and Methods` introduces practically important 58and useful mechanisms for the inclusion of components written in other languages 59into a program written in |LANG|. 60 61Section :ref:`Final Classes and Methods` discusses the well-known feature that 62in many OOP languages provides a way to restrict class inheritance and method 63overriding. 64 65Making a class *final* prohibits defining classes derived from it, whereas 66making a method *final* prevents it from overriding in derived classes. 67 68Section :ref:`Extension Functions` defines the ability to extend a class or an 69interface with new functionality without having to inherit from the class. This 70feature can be used for GUI programming (:ref:`Support for GUI Programming`). 71 72Section :ref:`Enumeration Methods` adds methods to declarations of the 73enumeration types. Such methods can help in some kinds of manipulations 74with *enums*. 75 76.. index:: 77 implementation 78 function overloading 79 method overloading 80 class final 81 method final 82 OOP (object-oriented programming) 83 inheritance 84 85Section :ref:`Exceptions` discusses the powerful, commonly used mechanism for 86the processing of various kinds of unexpected events and situations that break 87the ‘ordinary’ program logic. There are constructs to raise (‘throw’) exceptions, 88‘catch’ them along the dynamic sequence of function calls, and handle them. 89Also, some support for exceptions is provided by the classes from the standard 90library (see :ref:`Standard Library`). 91 92**Note**: The exceptions mechanism is sometimes deprecated for being too 93time-consuming and unsafe. Some modern languages do not support the 94exceptions mechanism as discussed in this section. That is why the expediency 95of adding this feature to the language is still under discussion. 96 97The |LANG| language supports writing concurrent applications in the form of 98*coroutines* (see :ref:`Coroutines`) that allow executing functions 99concurrently, while the *channels* through which the coroutines can produce 100results are asynchronous. 101 102There is a basic set of language constructs that support concurrency. A function 103that is to be launched asynchronously is marked by adding the ``async`` modifier 104to its declaration. In addition, any function---or lambda expression---can be 105launched as a separate thread explicitly by using the launch expression. 106 107.. index:: 108 exception 109 construct 110 coroutine 111 channel 112 function 113 async modifier 114 launch expression 115 launch 116 117The ``await`` statement is introduced to synchronize functions launched as 118threads. The generic class ``Promise<T>`` from the standard library (see 119:ref:`Standard Library`) is used to exchange information between threads. 120The class can be handled as an implementation of the channel mechanism. 121The class provides a number of methods to manipulate the values produced 122by threads. 123 124Section :ref:`Packages` discusses a well-known and proven language feature 125intended to organize large pieces of software that typically consist of many 126components. *Packages* allow developers to construct a software product 127as a composition of subsystems, and organize the development process in a way 128that is appropriate for independent teams to work in parallel. 129 130.. index:: 131 await statement 132 function 133 launch 134 generic class 135 standard library 136 implementation 137 channel 138 package 139 construct 140 141*Package* is the language construct that combines a number of declarations, 142and makes them parts of an independent compilation unit. 143 144The *export* and *import* features are used to organize communication 145between *packages*. An entity exported from one package becomes known to--- 146and accessible in---another package which imports that feature. Various 147options are provided to simplify export/import, e.g., by defining 148non-exported, i.e., ‘*internal*’ declarations that are not accessible from 149the outside of the package. 150 151In addition, the |LANG| supports the *package* initialization semantics that 152makes a *package* even more independent from the environment. 153 154In addition to the notion of *generic constructs*, the *declaration-site 155variance* feature is also considered. The idea of the feature is briefly 156described below, and in greater detail in :ref:`Generics Declaration-Site Variance`. 157 158.. index:: 159 package 160 construct 161 declaration 162 compilation unit 163 export 164 import 165 internal declaration 166 non-exported declaration 167 access 168 initialization 169 declaration-site variance 170 171Normally, two different argument types that specialize a generic class are 172handled as different and unrelated types (*invariance*). |LANG| proposes 173to extend the rule, and to allow such specializations become base classes and 174derived classes (*covariance*), or vice versa (*contravariance*), depending on 175the relationship of inheritance between argument types. 176 177Special markers are used to specify the *declaration-site variance*. 178The markers are to be added to generic parameter declarations. 179 180The practices of some languages (e.g., Scala) have proven the usefulness of 181this powerful mechanism. However, its practical usage can be relatively 182difficult. Therefore, whether to add this feature to the language or not 183is still under consideration. 184 185.. index:: 186 generic class 187 argument type 188 invariance 189 contravariance 190 covariance 191 generic parameter declaration 192 inheritance 193 derived class 194 base class 195 declaration-site variance 196 197| 198 199.. _Character Type and Literals: 200 201Character Type and Literals 202*************************** 203 204.. _Character Literals: 205 206Character Literals 207================== 208 209.. meta: 210 frontend_status: Done 211 212A *char literal* represents the following: 213 214- A value with a single character; or 215- A single escape sequence preceded by the characters 'single quote' (U+0027) 216 and 'c' (U+0063), and followed by a 'single quote' U+0027). 217 218| 219 220.. code-block:: abnf 221 222 CharLiteral: 223 'c\'' SingleQuoteCharacter '\'' 224 ; 225 226 SingleQuoteCharacter: 227 ~['\\\r\n] 228 | '\\' EscapeSequence 229 ; 230 231Examples: 232 233.. code-block:: typescript 234 :linenos: 235 236 c'a' 237 c'\n' 238 c'\x7F' 239 c'\u0000' 240 241*Character Literals* are of type *char*. 242 243.. index:: 244 char literal 245 character 246 escape sequence 247 single quote 248 type char 249 250| 251 252.. _Character Type and Operations: 253 254Character Type and Operations 255============================= 256 257.. meta: 258 frontend_status: Partly 259 260+---------+----------------------------------+--------------------------+ 261| Type | Type's Set of Values | Corresponding Class Type | 262+=========+==================================+==========================+ 263| *char* | Symbols with codes from \U+0000 | *Char* | 264| | to \U+FFFF inclusive, that is, | | 265| | from 0 to 65,535 | | 266+---------+----------------------------------+--------------------------+ 267 268|LANG| provides a number of operators to act on character values as discussed 269below. 270 271- Comparison operators that produce a value of type *boolean*: 272 273 + Character comparison operators '<', '<=', '>', and '>=' (see :ref:`Numerical Comparison Operators`); 274 + Character equality operators '==' and '!=' (see :ref:`Value Equality Operators`); 275 276- Character operators that produce a value of type *char*; 277 278 + Unary plus '+' and minus '-' operators (see :ref:`Unary Plus` and :ref:`Unary Minus`); 279 + Additive operators '+' and '-' (see :ref:`Additive Expressions`); 280 + Increment operator '++' used as prefix (see :ref:`Prefix Increment`) or 281 postfix (see :ref:`Postfix Increment`); 282 + Decrement operator '--' used as prefix (see :ref:`Prefix Decrement`) or 283 postfix (see :ref:`Postfix Decrement`); 284 285- Conditional operator '?:' (see :ref:`Conditional Expressions`); 286- The string concatenation operator '+' (see :ref:`String Concatenation`) that, 287 if one operand is ``string`` and the other is ``character``, converts the 288 character operand to a string, and then creates a concatenation of the 289 two strings as a new ``string``. 290 291The class *Char* provides constructors, methods, and constants 292that are parts of the |LANG| standard library (see :ref:`Standard Library`). 293 294.. index:: 295 char 296 Char 297 boolean 298 comparison operator 299 equality operator 300 unary operator 301 additive operator 302 increment operator 303 postfix 304 prefix 305 decrement operator 306 conditional operator 307 concatenation operator 308 operand 309 constructor 310 method 311 constant 312 313| 314 315.. _Array Creation Expressions: 316 317Array Creation Expressions 318************************** 319 320.. meta: 321 frontend_status: Done 322 323An *array creation expression* creates new objects that are instances of arrays. 324The *array literal* expression is used to create an array instance, and to 325provide some initial values (see :ref:`Array Literal`). 326 327.. code-block:: typescript 328 :linenos: 329 330 newArrayInstance: 331 'new' typeReference dimensionExpression+ 332 ; 333 334 dimensionExpression: 335 '[' expression ']' 336 ; 337 338.. code-block:: typescript 339 :linenos: 340 341 let x = new number[2][2] // create 2x2 matrix 342 343An *array creation expression* creates an object that is a new array with the 344elements of the type specified by *typeReference*. 345 346The type of each *dimensionExpression* must be convertible (see 347:ref:`Primitive Types Conversions`) to an integer type. 348A :index:`compile-time error` occurs otherwise. 349 350A numeric conversion (see :ref:`Primitive Types Conversions`) is 351performed on each *dimensionExpression* to ensure that the resultant type 352is *int*. A :index:`compile-time error` occurs otherwise. 353 354A :index:`compile-time error` occurs if any *dimensionExpression* is a 355constant expression that is evaluated at compile time to a negative integer 356value. 357 358If the type of any *dimensionExpression* is number or other floating-point 359type, and its fractional part is different from 0, then errors occur as 360follows: 361 362- Runtime error, if the situation is identified during program execution; and 363- Compile-time error, if the situation is detected during compilation. 364 365 366.. code-block:: typescript 367 :linenos: 368 369 let x = new number[-3] // compile-time error 370 371 let y = new number[3.141592653589] // compile-time error 372 373 foo (3.141592653589) 374 function foo (size: number) { 375 let y = new number[size] // runtime error 376 } 377 378 379A :index:`compile-time error` occurs if *typeReference* refers to a class 380that does not contain an accessible parameterless constructor, or if 381*typeReference* has no a default value. 382 383.. code-block:: typescript 384 :linenos: 385 386 let x = new string[3] // compile-time error: string has no default value 387 388 389.. index:: 390 array creation expression 391 object 392 instance 393 array 394 array literal 395 array instance 396 initial value 397 conversion 398 integer type 399 numeric conversion 400 type int 401 402| 403 404.. _Runtime Evaluation of Array Creation Expressions: 405 406Runtime Evaluation of Array Creation Expressions 407================================================ 408 409.. meta: 410 frontend_status: Partly 411 412The evaluation of an array creation expression at runtime is performed 413as follows: 414 415#. The dimension expressions are evaluated. The evaluation is performed 416 left-to-right; if any expression evaluation completes abruptly, then 417 the expressions to the right of it are not evaluated. 418 419#. The values of dimension expressions are checked. If the value of any 420 *dimExpr* expression is less than zero, then *NegativeArraySizeException* 421 is thrown. 422 423#. Space for the new array is allocated. If the available space is not 424 sufficient to allocate the array, then *OutOfMemoryError* is thrown, 425 and the evaluation of the array creation expression completes abruptly. 426 427#. When a one-dimensional array is created, each element of that array 428 is initialized to its default value if the type default value is defined 429 (:ref:`Default Values for Types`). 430 If the default value for an element type is not defined, but the element 431 type is a class type, then its *parameterless* constructor is used to 432 create each element’s value. 433 434#. When a multi-dimensional array is created, the array creation effectively 435 executes a set of nested loops of depth *n-1*, and creates an implied 436 array of arrays. 437 438.. index:: 439 array 440 constructor 441 expression 442 evaluation 443 default value 444 parameterless constructor 445 class type 446 initialization 447 nested loop 448 449| 450 451.. _Indexable Types: 452 453Indexable Types 454*************** 455 456.. meta: 457 frontend_status: None 458 459If a class or an interface declares one or two functions with names *$_get* and 460*$_set*, and signatures *(index: Type1): Type2* and *(index: Type1, value: Type2)* 461respectively, then an indexing expression (see :ref:`Indexing Expression`) can 462be applied to variables of such types: 463 464.. code-block:: typescript 465 :linenos: 466 467 class SomeClass { 468 $_get (index: number): SomeClass { return this } 469 $_set (index: number, value: SomeClass) { } 470 } 471 let x = new SomeClass 472 x = x[1] // This notation implies a call: x = x.$_get (1) 473 x[1] = x // This notation implies a call: x.$_set (1, x) 474 475If only one function is present, then only the appropriate form of the index 476expression (see :ref:`Indexing Expression`) is available: 477 478.. code-block:: typescript 479 :linenos: 480 481 class ClassWithGet { 482 $_get (index: number): ClassWithGet { return this } 483 } 484 let getClass = new ClassWithGet 485 getClass = getClass[0] 486 getClass[0] = getClass // Error - no $_set function available 487 488 489 class ClassWithSet { 490 $_set (index: number, value: ClassWithSet) { } 491 } 492 let setClass = new ClassWithSet 493 setClass = setClass[0] // Error - no $_get function available 494 setClass[0] = setClass 495 496Type *string* can be used as a type of the index parameter: 497 498.. code-block:: typescript 499 :linenos: 500 501 class SomeClass { 502 $_get (index: string): SomeClass { return this } 503 $_set (index: string, value: SomeClass) { } 504 } 505 let x = new SomeClass 506 x = x["index string"] 507 // This notation implies a call: x = x.$_get ("index string") 508 x["index string"] = x 509 // This notation implies a call: x.$_set ("index string", x) 510 511Functions *$_get* and *$_set* are ordinary functions with compiler-known 512signatures. The functions can be used like any other function. 513The functions can be abstract or defined in an interface and implemented later. 514The functions can be overridden and provide a dynamic dispatch for the indexing 515expression evaluation (see :ref:`Indexing Expression`). They can be used in 516generic classes and interfaces for better flexibility. 517 518A compile-time error occurs if these functions are marked as *async*. 519 520.. code-block:: typescript 521 :linenos: 522 523 interface ReadonlyIndexable<K, V> { 524 $_get (index: K): V 525 } 526 527 interface Indexable<K, V> extends ReadonlyIndexable<K, V> { 528 $_set (index: K, value: V) 529 } 530 531 class IndexableByNumber<V> extends Indexable<number, V> { 532 private data: V[] = [] 533 $_get (index: number): V { return this.data [index] } 534 $_set (index: number, value: V) { this.data[index] = value } 535 } 536 537 class IndexableByString<V> extends Indexable<string, V> { 538 private data = new Map<string, V> 539 $_get (index: string): V { return this.data [index] } 540 $_set (index: string, value: V) { this.data[index] = value } 541 } 542 543 class BadClass extends IndexableByNumber<boolean> { 544 override $_set (index: number, value: boolean) { index / 0 } 545 } 546 547 let x: IndexableByNumber<boolean> = new BadClass 548 x[666] = true // This will be dispatched at runtime to the overridden 549 // version of the $_set method 550 x.$_get (15) // $_get and $_set can be called as ordinary 551 // methods 552 553 554| 555 556 557.. _Iterable Types: 558 559Iterable Types 560************** 561 562.. meta: 563 frontend_status: None 564 565A class or an interface can be made *iterable*, meaning that their instances 566can be used in for-of statements (see :ref:`For-Of Statements`). 567 568A type is *iterable* if it declares a parameterless function with name 569*$_iterator* and signature *(): ITER*, where *ITER* is a type that implements 570*Iterator* interface defined in the standard library (see :ref:`Standard Library`). 571 572The example below defines *iterable* class *C*: 573 574.. code-block:: typescript 575 :linenos: 576 577 class C { 578 data: string[] = ['a', 'b', 'c'] 579 $_iterator() { 580 return new CIterator(this) 581 } 582 } 583 584 class CIterator implements Iterator<string> { 585 index = 0 586 base: C 587 constructor (base: C) { 588 this.base = base 589 } 590 next(): IteratorResult<string> { 591 return { 592 done: this.index >= this.base.data.length, 593 value: this.base.data[this.index++] 594 } 595 } 596 } 597 598 let c = new C() 599 for (let x of c) { 600 console.log(x) 601 } 602 603In the example above, class *C* function *$_iterator* returns 604*CIterator<string>*, which implements *Iterator<string>*. If executed, 605this code prints out the following: 606 607.. code-block:: typescript 608 609 "a" 610 "b" 611 "c" 612 613 614The function *$_iterator* is an ordinary function with a compiler-known 615signature. The function can be used like any other function. It can be 616abstract or defined in an interface to be implemented later. 617 618A compile-time error occurs if this function is marked as *async*. 619 620**Note**: To support the code compatible with |TS|, the name of the function 621*$_iterator* can be written as [*Symbol.iterator*]. In this case, the class 622*iterable* looks as follows: 623 624.. code-block:: typescript 625 :linenos: 626 627 class C { 628 data: string[] = ['a', 'b', 'c']; 629 [Symbol.iterator]() { 630 return new CIterator(this) 631 } 632 } 633 634The use of the name [*Symbol.iterator*] is considered deprecated. 635It can be removed in the future versions of the language. 636 637 638.. _Statements Experimental: 639 640Statements 641********** 642 643.. meta: 644 frontend_status: Done 645 646| 647 648 649.. _For-of Type Annotation: 650 651For-of Type Annotation 652====================== 653 654.. meta: 655 frontend_status: Done 656 657An explicit type annotation is allowed for a *for variable*: 658 659.. code-block:: typescript 660 :linenos: 661 662 // explicit type is used for a new variable, 663 let x: number[] = [1, 2, 3] 664 for (let n: number of x) { 665 console.log(n) 666 } 667 668.. index:: 669 explicit type annotation 670 671| 672 673.. _Multiple Catch Clauses in Try Statements: 674 675Multiple Catch Clauses in Try Statements 676======================================== 677 678.. meta: 679 frontend_status: Done 680 681When an exception or an error is thrown in the ``try`` block, or in a *throwing* 682(see :ref:`Throwing Functions`) or *rethrowing* (:ref:`Rethrowing Functions`) 683function called from the ``try`` block, the control is transferred to 684the first *catch* clause if the statement has at least one *catch* clause 685that can catch that exception or error. If no *catch* clause is found, then 686*exception* or *error* is propagated to the surrounding scope. 687 688**Note**: An exception handled within a *non-throwing* function (see 689:ref:`Non-Throwing Functions`) is never propagated outside that function. 690 691A *catch* clause has two parts: 692 693- An exception parameter that provides access to the object associated 694 with the exception or the error occurred; and 695 696- A block of code that is to handle the situation. 697 698.. index:: 699 exception 700 error 701 throwing function 702 rethrowing function 703 non-throwing function 704 try block 705 control transfer 706 catch clause 707 propagation 708 surrounding scope 709 exception parameter 710 access 711 712*Default catch clause* is a *catch* clause with the exception parameter type 713omitted. Such a *catch* clause handles any exception or error that is not 714handled by any previous clause. The type of that parameter is of the class 715*Object*. 716 717A :index:`compile-time error` occurs if: 718 719- The default *catch* clause is not the last *catch* clause in a ``try`` 720 statement. 721 722- The type reference of an exception parameter (if any) is neither the 723 class *Exception* or *Error*, nor a class derived from *Exception* or 724 *Error*. 725 726.. code-block:: typescript 727 :linenos: 728 729 class ZeroDivisor extends Exception {} 730 731 function divide(a: int, b: int): int throws { 732 if (b == 0) throw new ZeroDivisor() 733 return a / b 734 } 735 736 function process(a: int; b: int): int { 737 try { 738 let res = divide(a, b) 739 740 // further processing ... 741 } 742 catch (d: ZeroDivisor) { return MaxInt } 743 catch (e) { return 0 } 744 } 745 746.. index:: 747 default catch clause 748 exception 749 exception parameter 750 error 751 Exception 752 Error 753 try statement 754 derived class 755 756All exceptions that the ``try`` block can throw are caught by the function 757'process'. Special handling is provided for the *ZeroDivisor* exception, 758and the handling of other *exceptions* and *errors* is different. 759 760*Catch* clauses do not handle every possible *exception* or *error* 761that can be thrown by the code in the ``try`` block. If no *catch* clause 762can handle the situation, then *exception* or *error* is propagated to 763the surrounding scope. 764 765**Note**: If a ``try`` statement (*default catch clause*) is placed inside 766a *non-throwing* function (see :ref:`Non-Throwing Functions`), then 767*exception* is never propagated. 768 769.. index:: 770 exception 771 try block 772 propagation 773 try statement 774 default catch clause 775 non-throwing function 776 777If a *catch* clause contains a block that corresponds to the *error*'s 778parameter, then it can only handle that *error*. 779 780The type of the *catch* clause parameter in a *default catch clause* is 781omitted. The *catch* clause can handle any *exceptions* or *errors* 782unhandled by the previous clauses. 783 784The type of a *catch* clause parameter (if any) must be of the class *Error* 785or *Exception*, or of another class derived from *Exception* or *Error*. 786 787.. index:: 788 exception 789 error 790 catch clause 791 default catch clause 792 derived class 793 Error 794 Exception 795 796.. code-block:: typescript 797 :linenos: 798 799 function process(a: int; b: int): int { 800 try { 801 return a / b 802 } 803 catch (x: DivideByZeroError) { return MaxInt } 804 } 805 806A *catch* clause handles the *DivideByZeroError* at runtime. Other errors 807are propagated to the surrounding scope if no *catch* clause is found. 808 809.. index:: 810 catch clause 811 runtime 812 error 813 propagation 814 surrounding scope 815 816| 817 818.. _Assert Statements Experimental: 819 820``Assert`` Statements 821===================== 822 823.. meta: 824 frontend_status: Done 825 826An ``assert`` statement can have one or two expressions. The first expression 827is of type *boolean*; the optional second expression is of type *string*. A 828:index:`compile-time error` occurs if the types of the expressions fail to match. 829 830.. code-block:: abnf 831 832 assertStatement: 833 'assert' expression (':' expression)? 834 ; 835 836*Assertions* control mechanisms that are not part of |LANG|, yet the 837language allows having assertions either *enabled* or *disabled*. 838 839.. index:: 840 assert statement 841 assertion 842 expression 843 boolean 844 string 845 846The execution of the *enabled* assertion starts from the evaluation of the 847*boolean* expression. An error is thrown if the expression evaluates to 848``false``. The second expression is then evaluated (if provided). Its 849value passes as the *error* argument. 850 851The execution of the *disabled* assertion has no effect whatsoever. 852 853.. index:: 854 assertion 855 execution 856 boolean 857 evaluation 858 argument 859 value 860 861.. code-block:: typescript 862 :linenos: 863 864 assert p != null 865 assert f.IsOpened() : "file must be opened" + filename 866 assert f.IsOpened() : makeReportMessage() 867 868| 869 870.. _Function and Method Overloading: 871 872Function and Method Overloading 873******************************* 874 875.. meta: 876 frontend_status: Done 877 878Like the |TS| language, |LANG| supports overload signatures that allow 879specifying several headers for a function or method with different signatures. 880Most other languages support a different form of overloading that specifies 881a separate body for each overloaded header. 882 883Both approaches have their advantages and disadvantages. The |LANG| 884experimental approach allows for improved performance as a specific body 885is executed at runtime. 886 887.. index:: 888 function overloading 889 method overloading 890 overload signature 891 header 892 function 893 method 894 signature 895 overloaded header 896 execution 897 runtime 898 899| 900 901.. _Function Overloading: 902 903Function Overloading 904==================== 905 906.. meta: 907 frontend_status: Done 908 909If a declaration scope declares two functions with the same name but 910different signatures that are not *override-equivalent* (see 911:ref:`Override-Equivalent Signatures`), then the functions' name is 912*overloaded*. 913 914This fact is not difficult, and cannot cause a :index:`compile-time error` 915on its own. 916No specific relationship is required between the return types, or between the 917*throws* clauses of the two functions with the same name but different 918signatures that are not *override-equivalent*. 919 920When calling a function, the number of actual arguments (and any explicit type 921arguments) and compile-time types of arguments is used at compile time to 922determine the signature of the function being called (see 923:ref:`Function Call Expression`). 924 925.. index:: 926 function overloading 927 declaration scope 928 signature 929 name 930 override-equivalent signature 931 overloaded function name 932 return type 933 throws clause 934 argument 935 actual argument 936 explicit type argument 937 function call 938 939 940| 941 942.. _Class Method Overloading: 943 944Class Method Overloading 945======================== 946 947.. meta: 948 frontend_status: Done 949 950If two methods within a class have the same name, and their signatures are not 951*override-equivalent*, then the methods' name is considered *overloaded*. 952 953An *overloaded* method name cannot cause a :index:`compile-time error` 954on its own. 955 956If the signatures of two methods with the same name are not *override-equivalent*, 957then the return types of those methods, or the *throws* or *rethrows* clauses 958of those methods can have any kind of relationship. 959 960A number of actual arguments, explicit type arguments, and compile-time types 961of the arguments is used at compile time to determine the signature of the 962method being called (see :ref:`Method Call Expression`, and 963:ref:`Step 2 Selection of Method`). 964 965In the case of an instance method, the actual method being called is determined 966at runtime by using the dynamic method lookup (see :ref:`Method Call Expression`) 967provided by the runtime system. 968 969.. index:: 970 class method overloading 971 signature 972 override-equivalent signature 973 throws clause 974 rethrows clause 975 explicit type argument 976 actual argument 977 method call 978 instance method 979 runtime 980 dynamic method lookup 981 982| 983 984.. _Interface Method Overloading: 985 986Interface Method Overloading 987============================ 988 989.. meta: 990 frontend_status: Done 991 992If two methods of an interface (declared or inherited in any combination) 993have the same name but different signatures that are not *override-equivalent* 994(see :ref:`Inheriting Methods with Override-Equivalent Signatures`), then 995such method name is considered *overloaded*. 996 997However, this causes no :index:`compile-time error` on its own, because no 998specific relationship is required between the return types, or between the 999*throws* clauses of the two methods. 1000 1001.. index:: 1002 interface method overriding 1003 interface 1004 method 1005 override-equivalent signature 1006 inherited method 1007 overloaded method 1008 method inheritance 1009 declared method 1010 return type 1011 throws clause 1012 signature 1013 1014| 1015 1016.. _Constructor Overloading: 1017 1018Constructor Overloading 1019======================= 1020 1021.. meta: 1022 frontend_status: Done 1023 1024The constructor overloading behaves identically to the method overloading (see 1025:ref:`Class Method Overloading`). Each class instance creation expression (see 1026:ref:`New Expressions`) resolves the overloading at compile time. 1027 1028.. index:: 1029 constructor overloading 1030 method overloading 1031 class instance creation expression 1032 1033| 1034 1035.. _Declaration Distinguishable by Signatures: 1036 1037Declaration Distinguishable by Signatures 1038========================================= 1039 1040.. meta: 1041 frontend_status: Done 1042 1043Declarations with the same name are distinguishable by signatures if: 1044 1045- They are functions with the same name, but their signatures are not 1046 *override-equivalent* (see :ref:`Override-Equivalent Signatures` and 1047 :ref:`Function Overloading`). 1048 1049- They are methods with the same name, but their signatures are not 1050 *override-equivalent* (see :ref:`Override-Equivalent Signatures`, 1051 :ref:`Class Method Overloading`, and :ref:`Interface Method Overloading`). 1052 1053- They are constructors of the same class, but their signatures are not 1054 *override-equivalent* (see :ref:`Override-Equivalent Signatures` and 1055 :ref:`Constructor Overloading`). 1056 1057.. index:: 1058 signature 1059 function overloading 1060 override-equivalent signature 1061 interface method overloading 1062 class method overloading 1063 1064 1065The example below is of functions distinguishable by signatures: 1066 1067.. code-block:: typescript 1068 :linenos: 1069 1070 function foo() {} 1071 function foo(x: number) {} 1072 function foo(x: number[]) {} 1073 function foo(x: string) {} 1074 1075The example below is of functions undistinguishable by signatures that cause a 1076:index:`compile-time error`: 1077 1078.. index:: 1079 function 1080 signature 1081 1082.. code-block:: typescript 1083 :linenos: 1084 1085 // Functions have override-equivalent signatures 1086 function foo(x: number) {} 1087 function foo(y: number) {} 1088 1089 // Functions have override-equivalent signatures 1090 function foo(x: number) {} 1091 type MyNumber = number 1092 function foo(x: MyNumber) {} 1093 1094| 1095 1096.. _Native Functions and Methods: 1097 1098Native Functions and Methods 1099**************************** 1100 1101.. meta: 1102 frontend_status: Done 1103 1104| 1105 1106.. _Native Functions: 1107 1108Native Functions 1109================ 1110 1111.. meta: 1112 frontend_status: Done 1113 1114A *native* function implemented in a platform-dependent code is typically 1115written in another programming language (e.g., *C*). 1116 1117A :index:`compile-time error` occurs if a *native* function has a body. 1118 1119.. index:: 1120 native function 1121 implementation 1122 platform-dependent code 1123 1124| 1125 1126.. _Native Methods Experimental: 1127 1128Native Methods 1129============== 1130 1131.. meta: 1132 frontend_status: Done 1133 1134*Native* methods are methods implemented in a platform-dependent code written 1135in another programming language (e.g., *C*). 1136 1137A :index:`compile-time error` occurs if: 1138 1139- A method declaration contains the keyword ``abstract`` along with the 1140 keyword ``native``. 1141 1142- A *native* method has a body (see :ref:`Method Body`) that is a block 1143 instead of a simple semicolon or empty body. 1144 1145.. index:: 1146 native method 1147 implementation 1148 platform-dependent code 1149 keyword native 1150 method body 1151 block 1152 method declaration 1153 keyword abstract 1154 1155| 1156 1157.. _Final Classes and Methods: 1158 1159Final Classes and Methods 1160************************* 1161 1162.. meta: 1163 frontend_status: Done 1164 1165| 1166 1167.. _Final Classes Experimental: 1168 1169Final Classes 1170============= 1171 1172.. meta: 1173 frontend_status: Done 1174 1175A class may be declared *final* to prevent its extension. A class declared 1176*final* cannot have subclasses, and no method of a *final* class can be 1177overridden. 1178 1179A :index:`compile-time error` occurs if the *extends* clause of a class 1180declaration contains another class that is *final*. 1181 1182.. index:: 1183 final class 1184 method 1185 overriding 1186 class 1187 class extension 1188 extends clause 1189 class declaration 1190 subclass 1191 1192| 1193 1194.. _Final Methods Experimental: 1195 1196Final Methods 1197============= 1198 1199.. meta: 1200 frontend_status: Done 1201 1202A method can be declared *final* to prevent it from being overridden (see 1203:ref:`Overriding by Instance Methods`) or hidden in subclasses. 1204 1205A :index:`compile-time error` occurs if: 1206 1207- A method declaration contains the keyword ``abstract`` or ``static`` 1208 along with the keyword ``final``. 1209 1210- A method declared *final* is overridden. 1211 1212.. index:: 1213 final method 1214 overriding 1215 instance method 1216 hiding 1217 subclass 1218 method declaration 1219 keyword abstract 1220 keyword static 1221 keyword final 1222 1223| 1224 1225.. _Default and Static Interface Methods: 1226 1227Default and Static Interface Methods 1228************************************ 1229 1230.. meta: 1231 frontend_status: Done 1232 1233| 1234 1235.. _Default Method Declarations: 1236 1237Default Method Declarations 1238============================ 1239 1240.. meta: 1241 frontend_status: Done 1242 1243.. code-block:: abnf 1244 1245 interfaceDefaultMethodDeclaration: 1246 'private'? identifier signature block 1247 ; 1248 1249A default method can be explicitly declared *private* in an interface body. 1250 1251A block of code that represents the body of a default method in an interface 1252provides a default implementation for any class if such class does not override 1253the method to implement the interface. 1254 1255.. index:: 1256 default method 1257 method declaration 1258 private 1259 implementation 1260 default method body 1261 interface body 1262 default implementation 1263 overriding 1264 1265| 1266 1267.. _Static Method Declarations: 1268 1269*Static* Method Declarations 1270============================ 1271 1272.. meta: 1273 frontend_status: Done 1274 1275.. code-block:: abnf 1276 1277 interfaceStaticMethodDeclaration: 1278 'static' 'private'? identifier signature block 1279 | 'private'? 'static' identifier signature block 1280 ; 1281 1282A *static* method in an interface body can be explicitly declared *private*. 1283 1284*Static* interface method calls refer to no particular object. 1285 1286In contrast to default methods, *static* interface methods are not instance 1287methods. 1288 1289.. index:: 1290 static method declaration 1291 static method 1292 interface body 1293 private 1294 static interface method 1295 default method 1296 instance method 1297 1298A :index:`compile-time error` occurs if: 1299 1300- The body of a *static* method attempts to use the keywords ``this`` or 1301 ``super`` to refer to the current or a supertype object. 1302 1303- The header or body of a *static* method of an interface contains the 1304 name of any surrounding declaration’s type parameter. 1305 1306.. index:: 1307 static method body 1308 keyword this 1309 keyword super 1310 static method header 1311 static method body 1312 interface 1313 type parameter 1314 surrounding declaration 1315 1316| 1317 1318.. _Extension Functions: 1319 1320Extension Functions 1321******************* 1322 1323.. meta: 1324 frontend_status: Partly 1325 todo: static extension functions, import/export of them, extension function for primitive types 1326 1327The *extension function* mechanism allows using a special form of top-level 1328functions as class or interface extensions. Syntactically, *extension* is the 1329addition of a new functionality. 1330 1331*Extensions* can be called in the usual way as if they were methods of the 1332original class. However, *extensions* do not actually modify the classes they 1333extend. No new member is inserted into a class; only new *extension functions* 1334are callable with the *dot-notation* on variables of the class. 1335 1336*Extension functions* are dispatched statically; what *extension function* 1337is being called is already known at compile time based on the receiver type 1338specified in the extension function declaration. 1339 1340.. index:: 1341 function 1342 class extension 1343 interface extension 1344 functionality 1345 function call 1346 original class 1347 class member 1348 extension function 1349 callable function 1350 dot-notation 1351 receiver type 1352 extension function declaration 1353 1354*Extension functions* specify names, signatures, and bodies: 1355 1356.. code-block:: abnf 1357 1358 extensionFunctionDeclaration: 1359 'static'? 'function' typeParameters? typeReference '.' identifier 1360 signature block 1361 ; 1362 1363The keyword ``this`` inside an extension function corresponds to the receiver 1364object (i.e., *typeReference* before the dot). 1365 1366Class or interface referred by typeReference, and *private* or *protected* 1367members are not accessible within the bodies of their *extension functions*. 1368Only *public* members can be accessed: 1369 1370.. index:: 1371 keyword this 1372 extension function 1373 receiver object 1374 1375.. code-block:: typescript 1376 :linenos: 1377 1378 class A { 1379 foo () { ... this.bar() ... } 1380 // Extension function bar() is accessible 1381 protected member_1 ... 1382 private member_2 ... 1383 } 1384 function A.bar () { ... 1385 this.foo() // Method foo() is accessible as it is public 1386 this.member_1 // Compile-time error as member_1 is not accessible 1387 this.member_2 // Compile-time error as member_2 is not accessible 1388 ... 1389 } 1390 let a = new A() 1391 a.foo() // Ordinary class method is called 1392 a.bar() // Class extension function is called 1393 1394*Extension functions* can be generic as illustrated by the example below: 1395 1396.. code-block:: typescript 1397 :linenos: 1398 1399 function <T> B<T>.foo(p: T) { 1400 console.log (p) 1401 } 1402 function demo (p1: B<SomeClass>, p2: B<BaseClass>) { 1403 p1.foo (new SomeClass()) 1404 // Type inference should determine the instantiating type 1405 p2.foo <BaseClass>(new DerivedClass()) 1406 // Explicit instantiation 1407 } 1408 1409*Extension functions* are top-level functions, and can call each other. The 1410form of such calls depends on whether static was used while declaring or not. 1411This affects the kind of receiver to be used for the call. A *static extension 1412function* requires the name of the type (class or interface). A *non-static 1413extension function* requires a variable as receiver: 1414 1415.. code-block:: typescript 1416 :linenos: 1417 1418 class A { 1419 foo () { ... 1420 this.bar() // non-static extension function is called with this. 1421 A.goo() // static extension function is called with class name receiver 1422 ... 1423 } 1424 } 1425 function A.bar () { ... 1426 this.foo() // Method foo() is called 1427 A.goo() // Other static extension function is called with class name receiver 1428 ... 1429 } 1430 static function A.goo () { ... 1431 this.foo() // Compile-time error as instance members are not accessible 1432 this.bar() // Compile-time error as instance extension functions are not accessible 1433 ... 1434 } 1435 let a = new A() 1436 a.foo() // Ordinary class method is called 1437 a.bar() // Class instance extension function is called 1438 A.goo() // Static extension function is called 1439 1440*Extension functions* are dispatched statically and remain active for all 1441derived classes until the next definition of the *extension function* for the 1442derived class is found: 1443 1444| 1445 1446.. code-block:: typescript 1447 :linenos: 1448 1449 class Base { ... } 1450 class Derived extends Base { ... } 1451 function Base.foo () { console.log ("Base.foo is called") } 1452 function Derived.foo () { console.log ("Derived.foo is called") } 1453 1454 let b: Base = new Base() 1455 b.foo() // `Base.foo is called` to be printed 1456 b = new Derived() 1457 b.foo() // `Base.foo is called` to be printed 1458 let d: Derived = new Derived() 1459 d.foo() // `Derived.foo is called` to be printed 1460 1461*Extension functions* can be: 1462 1463- Put into a compilation unit other than class or interface; and 1464- Imported by using a name of the *extension function*. 1465 1466.. code-block:: typescript 1467 :linenos: 1468 1469 // file a.ets 1470 import {bar} from "a.ets" // import name 'bar' 1471 class A { 1472 foo () { ... 1473 this.bar() // non-static extension function is called with this. 1474 A.goo() // static extension function is called with class name receiver 1475 ... 1476 } 1477 } 1478 1479 // file ext.ets 1480 import {A} from "a.ets" // import name 'A' 1481 function A.bar () { ... 1482 this.foo() // Method foo() is called 1483 ... 1484 } 1485 1486If an *extension function* and a type method have the same name and signature, 1487then calls to that name are routed to the method: 1488 1489.. code-block:: typescript 1490 :linenos: 1491 1492 class A { 1493 foo () { console.log ("Method A.foo is called") } 1494 } 1495 function A.foo () { console.log ("Extension A.foo is called") } 1496 let a = new A() 1497 a.foo() // Method is called, `Method A.foo is called` to be printed out 1498 1499The precedence between methods and *extension functions* can be expressed 1500by the following formula: 1501 1502 derived type instance method < 1503 base type instance method < 1504 derived type extension function < 1505 base type extension function. 1506 1507In other words, the priority of standard object-oriented semantics is higher 1508than that of type extension functions: 1509 1510| 1511 1512.. code-block:: typescript 1513 :linenos: 1514 1515 class Base { 1516 foo () { console.log ("Method Base.foo is called") } 1517 } 1518 class Derived extends Base { 1519 override foo () { console.log ("Method Derived.foo is called") } 1520 } 1521 function Base.foo () { console.log ("Extension Base.foo is called") } 1522 function Derived.foo () { console.log ("Extension Derived.foo is called") } 1523 1524 let b: Base = new Base() 1525 b.foo() // `Method Base.foo is called` to be printed 1526 b = new Derived() 1527 b.foo() // `Method Derived.foo is called` to be printed 1528 let d: Derived = new Derived() 1529 d.foo() // `Method Derived.foo is called` to be printed 1530 1531If an *extension function* and another top-level function have the same name 1532and signature, then calls to this name are routed to a proper function in 1533accordance with the form of the call. *Extension functions* cannot be called 1534without a receiver as they have access to ``this``. 1535 1536.. code-block:: typescript 1537 :linenos: 1538 1539 class A { ... } 1540 function A.foo () { console.log ("Extension A.foo is called") } 1541 function foo () { console.log ("Top-level foo is called") } 1542 let a = new A() 1543 a.foo() // Extension function is called, `Extension A.foo is called` to be printed out 1544 foo () // Top-level function is called, `Top-level foo is called` to be printed out 1545 1546 1547| 1548 1549.. _Trailing Lambda: 1550 1551Trailing Lambda 1552*************** 1553 1554.. meta: 1555 frontend_status: Done 1556 1557The *trailing lambda* mechanism allows using a special form of function 1558or method call when the last parameter of a function or a method is of 1559function type, and the argument is passed as a lambda using the ``{}`` 1560notation. 1561 1562Syntactically, the *trailing lambda* looks as follows: 1563 1564.. index:: 1565 trailing lambda 1566 function call 1567 method call 1568 function parameter 1569 method parameter 1570 lambda 1571 function type 1572 1573.. code-block:: typescript 1574 :linenos: 1575 1576 class A { 1577 foo (f: ()=>void) { ... } 1578 } 1579 1580 let a = new A() 1581 a.foo() { console.log ("method lambda argument is activated") } 1582 // method foo receives last argument as an inline lambda 1583 1584The formal syntax of the *trailing lambda* is presented below: 1585 1586| 1587 1588.. code-block:: abnf 1589 1590 trailingLambdaCall: 1591 ( objectReference '.' identifier typeArguments? 1592 | expression ('?.' | typeArguments)? 1593 ) 1594 arguments block 1595 ; 1596 1597 1598Currently, no parameter can be specified for the trailing lambda. A 1599compile-time error occurs otherwise. 1600 1601**Note**: If a call is followed by a block, and the function or method 1602being called has no last function type parameter, then such block is 1603handled as an ordinary block of statements but not as a lambda function. 1604 1605In case of other ambiguities---e.g., when a function or method call has 1606the last parameter, which can be optional, of a function type---the syntax 1607production that starts with '{' following the function or method call is 1608handled as the *trailing lambda*. 1609If other semantics is needed, then a separating semicolon ';' can be used. 1610It means that the function or the method is to be called without the last 1611argument (see :ref:`Optional Parameters`). 1612 1613.. code-block:: typescript 1614 :linenos: 1615 1616 class A { 1617 foo (p?: ()=>void) { ... } 1618 } 1619 1620 let a = new A() 1621 a.foo() { console.log ("method lambda argument is activated") } 1622 // method foo receives last argument as an inline lambda 1623 1624 a.foo(); { console.log ("that is the block code") } 1625 // method 'foo' is called with 'p' parameter set to 'undefined' 1626 // ';' allows to specify explicitly that '{' starts the block 1627 1628 function bar(f: ()=>void) { ... } 1629 1630 bar() { console.log ("function lambda argument is activated") } 1631 // function 'bar' receives last argument as an inline lambda, 1632 bar(); { console.log ("that is the block code") } 1633 // function 'bar' is called with 'p' parameter set to 'undefined' 1634 1635.. index:: 1636 trailing lambda 1637 compile-time error 1638 call 1639 block 1640 statement 1641 function 1642 method 1643 lambda function 1644 function type parameter 1645 1646.. code-block:: typescript 1647 :linenos: 1648 1649 function foo (f: ()=>void) { ... } 1650 function bar (n: number) { ... } 1651 1652 foo() { console.log ("function lambda argument is activated") } 1653 // function foo receives last argument as an inline lambda, 1654 1655 bar(5) { console.log ("after call of 'bar' this block is executed") } 1656 1657 foo(() => { console.log ("function lambda argument is activated") }) 1658 { console.log ("after call of 'foo' this block is executed") } 1659 /* here, function foo receives lambda as an argument and a block after 1660 the call is just a block, not a trailing lambda. */ 1661 1662| 1663 1664.. _Enumeration SuperType: 1665 1666Enumeration Super Type 1667********************** 1668 1669.. meta: 1670 frontend_status: Partly 1671 1672Any *enum* type has class type *Object* as its supertype. This allows 1673polymorphic assignments into *Object* type variables. The *instanceof* 1674check can be used to get enumeration variable back by applying 'as' conversion. 1675 1676.. code-block:: typescript 1677 :linenos: 1678 1679 enum Commands { Open = "fopen", Close = "fclose" } 1680 let c: Commands = Commands.Open 1681 let o: Object = c // Autoboxing of enum type to its reference version 1682 // Such reference version type has no name, but can be detected by instanceof 1683 if (o.instanceof (Commands)) { 1684 c = o as Commands // And explicitly converted back by 'as' conversion 1685 } 1686 1687.. index:: 1688 enum type 1689 class type 1690 Object 1691 supertype 1692 polymorphic assignment 1693 type variable 1694 enumeration variable 1695 conversion 1696 1697| 1698 1699.. _Enumeration Types Conversions: 1700 1701Enumeration Types Conversions 1702============================= 1703 1704.. meta: 1705 frontend_status: Partly 1706 1707Every *enum* type is compatible (see :ref:`Type Compatibility`) with type 1708*Object* (see :ref:`Enumeration SuperType`). Every variable of *enum* type can 1709thus be assigned into a variable of type *Object*. 1710 1711.. index:: 1712 enum type 1713 compatibility 1714 Object 1715 variable 1716 assignment 1717 mutable variable 1718 1719 1720| 1721 1722.. _Enumeration Methods: 1723 1724Enumeration Methods 1725******************* 1726 1727.. meta: 1728 frontend_status: Partly 1729 1730There are several static methods available to handle each enumeration type: 1731 1732- 'values()' returns an array of enumeration constants in the order of 1733 declaration. 1734- 'valueOf(name: string)' returns an enumeration constant with the given 1735 name, or throws an error if no constant with such name exists. 1736 1737.. index:: 1738 enumeration method 1739 static method 1740 enumeration type 1741 enumeration constant 1742 error 1743 constant 1744 1745.. code-block:: typescript 1746 :linenos: 1747 1748 enum Color { Red, Green, Blue } 1749 let colors = Color.values() 1750 //colors[0] is the same as Color.Red 1751 let red = Color.valueOf("Red") 1752 1753There is an additional method for instances of any enumeration type: 1754 1755- 'getValue()' returns a value of enumeration constant which is 1756 either of ``int`` or ``string`` type. 1757 1758.. code-block:: typescript 1759 :linenos: 1760 1761 enum Color { Red, Green = 10, Blue } 1762 let c: Color = Color.Green 1763 console.log(c.getValue()) // prints 10 1764 1765**Note**: ``c.toString()`` returns the same value as ``c.getValue()``; its 1766type must be converted to *string* for enumeration constants of a numeric type. 1767 1768.. index:: 1769 instance 1770 enumeration type 1771 value 1772 numeric type 1773 enumeration constant 1774 type int 1775 type string 1776 1777| 1778 1779.. _Exceptions: 1780 1781Exceptions 1782********** 1783 1784.. meta: 1785 frontend_status: Done 1786 1787*Exception* is the base class of all exceptions. *Exception* is used to 1788define a new exception, or any class derived from the *Exception* as the 1789base of a class: 1790 1791.. code-block:: typescript 1792 :linenos: 1793 1794 class MyException extends Exception { ... } 1795 1796.. index:: 1797 exception 1798 base class 1799 Exception 1800 1801A :index:`compile-time error` occurs if a generic class is a direct or 1802indirect subclass of *Exception*. 1803 1804An *exception* is thrown explicitly with the ``throw`` statement. 1805 1806When an *exception* is thrown, the surrounding piece of code is to handle it by 1807correcting the problem, trying an alternative approach, or informing the user. 1808 1809There are two ways to process an *exception*: 1810 1811- Propagating the exception from a function to the code that calls that 1812 function (see :ref:`Throwing Functions`); 1813 1814- Using a ``try`` statement to handle the exception (see :ref:`Try Statements`). 1815 1816.. index:: 1817 exception 1818 base class 1819 Exception 1820 try statement 1821 propagation 1822 function 1823 throwing function 1824 function call 1825 1826| 1827 1828.. _Throwing Functions: 1829 1830Throwing Functions 1831================== 1832 1833.. meta: 1834 frontend_status: Done 1835 1836The keyword ``throws`` is used at the end of a signature to indicate that a 1837function (this notion here includes methods, constructors, or lambdas) can 1838throw an exception. A function ending with ``throws`` is called a 1839*throwing function*. The function type can also be marked as ``throws``. 1840 1841.. index:: 1842 keyword throws 1843 throwing function 1844 signature 1845 method 1846 constructor 1847 lambda 1848 function 1849 exception 1850 function type 1851 throws mark 1852 1853.. code-block:: typescript 1854 :linenos: 1855 1856 function canThrow(x: int): int throws { ... } 1857 1858A *throwing function* can propagate exceptions to the scope from which 1859it is called. The propagation of an *exception* occurs if: 1860 1861- The call of a *throwing function* is not enclosed in a ``try`` statement; or 1862 1863- The enclosed ``try`` statement does not contain a clause that can catch the 1864 exception. 1865 1866 1867In the example below, the function call is not enclosed in a ``try`` 1868statement; any exception raised by *canThrow* function is propagated: 1869 1870.. index:: 1871 throwing function 1872 propagation 1873 exception 1874 scope 1875 function call 1876 try statement 1877 1878.. code-block:: typescript 1879 :linenos: 1880 1881 function propagate1(x: int): int throws { 1882 return y = canThrow(x) // exception is propagated 1883 } 1884 1885 1886In the example below, the ``try`` statement can catch only ``this`` exceptions. 1887Any exception raised by *canThrow* function---but for *MyException* itself, and 1888any exception derived from *MyException*---is propagated: 1889 1890.. index:: 1891 try statement 1892 this 1893 exception 1894 propagation 1895 1896.. code-block:: typescript 1897 :linenos: 1898 1899 function propagate2(x: int): int throws { 1900 try { 1901 return y = canThrow(x) // 1902 } 1903 catch (e: MyException) /*process*/ } 1904 return 0 1905 } 1906 1907.. _Non-Throwing Functions: 1908 1909Non-Throwing Functions 1910====================== 1911 1912.. meta: 1913 frontend_status: Done 1914 1915A *non-throwing function* is a function (this notion here includes methods, 1916constructors, or lambdas) not marked as ``throws``. Any exceptions inside a 1917*non-throwing function* must be handled inside the function. 1918 1919A :index:`compile-time error` occurs if not **all** of the following 1920requirements are met: 1921 1922- The call of a *throwing function* is enclosed in a ``try`` statement; 1923 1924- The enclosing ``try`` statement has a default *catch* clause. 1925 1926.. index:: 1927 non-throwing function 1928 throwing function 1929 function 1930 method 1931 constructor 1932 lambda 1933 throws mark 1934 try statement 1935 catch clause 1936 1937 1938.. code-block:: typescript 1939 :linenos: 1940 1941 // non-throwing function 1942 function cannotThrow(x: int): int { 1943 return y = canThrow(x) // compile-time error 1944 } 1945 1946 function cannotThrow(x: int): int { 1947 try { 1948 return y = canThrow(x) // 1949 } 1950 catch (e: MyException) { /* process */ } 1951 // compile-time error – default catch clause is required 1952 } 1953 1954| 1955 1956.. _Rethrowing Functions: 1957 1958Rethrowing Functions 1959==================== 1960 1961.. meta: 1962 frontend_status: Done 1963 1964A *rethrowing function* is a function that accepts a *throwing function* as a 1965parameter, and is marked with the keyword ``rethrows``. 1966 1967The body of such function must not contain any ``throw`` statement that is 1968not handled by a ``try`` statement within that body. A function with unhandled 1969``throw`` statements must be marked with the keyword ``throws`` but not 1970``rethrows``. 1971 1972.. index:: 1973 rethrowing function 1974 throwing function 1975 non-throwing function 1976 function parameter 1977 keyword throws 1978 keyword rethrows 1979 try statement 1980 throw statement 1981 1982Both a *throwing* and a *non-throwing* function can be an argument of a 1983*rethrowing function* *foo* that is being called. 1984 1985If a *throwing function* is an argument, then the calling of *foo* can 1986throw an exception. 1987 1988This rule is exception-free, i.e., a *non-throwing* function used as a call 1989argument cannot throw an exception: 1990 1991.. code-block:: typescript 1992 :linenos: 1993 1994 function foo (action: () throws) rethrows { 1995 action() 1996 } 1997 1998 function canThrow() { 1999 /* body */ 2000 } 2001 2002 function cannotThrow() { 2003 /* body */ 2004 } 2005 2006 // calling rethrowing function: 2007 foo(canThrow) // exception can be thrown 2008 foo(cannotThrow) // exception-free 2009 2010A call is exception-free if: 2011 2012- Function *foo* has several parameters of a function type marked 2013 with *throws*; and 2014 2015- All actual arguments of the call to *foo* are non-throwing. 2016 2017However, the call can raise an exception, and is handled as any other 2018*throwing function* call if at least one of the actual function arguments 2019is *throwing*. 2020 2021It implies that a call to *foo* within the body of a *non-throwing* function 2022must be guaranteed with a ``try-catch`` statement. 2023 2024.. index:: 2025 function 2026 exception-free call 2027 function type parameter 2028 throws mark 2029 throwing function 2030 non-throwing function 2031 try-catch statement 2032 2033.. code-block:: typescript 2034 :linenos: 2035 2036 function mayThrowContext() throws { 2037 // calling rethrowing function: 2038 foo(canThrow) // exception can be thrown 2039 foo(cannotThrow) // exception-free 2040 } 2041 2042 function neverThrowsContext() { 2043 try { 2044 // calling rethrowing function: 2045 foo(canThrow) // exception can be thrown 2046 foo(cannotThrow) // exception-free 2047 } 2048 catch (e) { 2049 // To handle the situation 2050 } 2051 } 2052 2053| 2054 2055.. _Exceptions and Initialization Expression: 2056 2057Exceptions and Initialization Expression 2058======================================== 2059 2060.. meta: 2061 frontend_status: Done 2062 2063A *variable declaration* (see :ref:`Variable Declarations`) or a *constant 2064declaration* (see :ref:`Constant Declarations`) expression used to initialize 2065a variable or constant must not have calls to functions that can *throw* or 2066*rethrow* exceptions if the declaration is not within a statement that handles 2067all exceptions. 2068 2069See :ref:`Throwing Functions` and :ref:`Rethrowing Functions` for details. 2070 2071.. index:: 2072 variable declaration 2073 exception 2074 initialization expression 2075 constant declaration 2076 expression 2077 initialization 2078 variable 2079 constant 2080 function call 2081 throw exception 2082 rethrow exception 2083 statement 2084 throwing function 2085 rethrowing function 2086 2087| 2088 2089.. _Exceptions and Errors Inside Field Initializers: 2090 2091Exceptions and Errors Inside Field Initializers 2092=============================================== 2093 2094.. meta: 2095 frontend_status: Done 2096 2097Class field initializers cannot call *throwing* or *rethrowing* functions. 2098 2099See :ref:`Throwing Functions` and :ref:`Rethrowing Functions` for details. 2100 2101.. index:: 2102 exception 2103 error 2104 field initializer 2105 throwing function 2106 rethrowing function 2107 2108| 2109 2110.. _Coroutines: 2111 2112Coroutines 2113********** 2114 2115.. meta: 2116 frontend_status: Partly 2117 2118A function or lambda can be a *coroutine*. |LANG| supports **basic coroutines**, 2119**structured coroutines*,* and communication **channels**. 2120Basic coroutines are used to create and launch a coroutine; the result is then 2121to be awaited. 2122 2123.. index:: 2124 structured coroutine 2125 basic coroutine 2126 function 2127 lambda 2128 coroutine 2129 channel 2130 launch 2131 2132| 2133 2134.. _Create and Launch a Coroutine: 2135 2136Create and Launch a Coroutine 2137============================= 2138 2139.. meta: 2140 frontend_status: Done 2141 2142The following expression is used to create and launch a coroutine: 2143 2144.. code-block:: typescript 2145 :linenos: 2146 2147 launchExpression: 'launch' expression; 2148 2149A :index:`compile-time error` occurs if the expression is not a *function call 2150expression* (see :ref:`Function Call Expression`). 2151 2152| 2153 2154.. code-block:: typescript 2155 :linenos: 2156 2157 let res = launch cof(10) 2158 2159 // where 'cof' can be defined as: 2160 function cof(a: int): int { 2161 let res: int 2162 // Do something 2163 return res 2164 } 2165 2166Lambda is used in the launch expression as follows: 2167 2168.. code-block:: typescript 2169 :linenos: 2170 2171 let res = launch (n: int) => { /* lambda body */(7) 2172 2173.. index:: 2174 expression 2175 coroutine 2176 launch 2177 function call expression 2178 lambda 2179 launch expression 2180 2181The launch expression result is of type *Promise<T>*, where *T* is the return 2182type of the function being called: 2183 2184.. code-block:: typescript 2185 :linenos: 2186 2187 function foo(): int {} 2188 function bar() {} 2189 let resfoo = launch foo() 2190 let resbar = launch bar() 2191 2192The type of *resfoo* in the example above is *Promise<int>*, and the 2193type of *resbar* is *Promise<void>*. 2194 2195Similarly to |TS|, |LANG| supports the launching of a coroutine by calling 2196the function *async* (see :ref:`Async Functions`). No restrictions apply as to 2197from what scope to call the function *async*. 2198 2199.. index:: 2200 launch expression 2201 return type 2202 function call 2203 coroutine 2204 function async 2205 restriction 2206 2207.. code-block:: typescript 2208 :linenos: 2209 2210 async function foo(): Promise<int> {} 2211 2212 // This will create and launch coroutine 2213 let resfoo = foo() 2214 2215| 2216 2217.. _Awaiting a Coroutine: 2218 2219Awaiting a Coroutine 2220==================== 2221 2222.. meta: 2223 frontend_status: Done 2224 2225The expressions *await* and *wait* are used while a previously launched 2226coroutine finishes and returns a value. 2227 2228.. code-block:: abnf 2229 2230 awaitExpresson: 2231 'await' expression 2232 ; 2233 2234A :index:`compile-time error` occurs if the expression type is not *Promise<T>*. 2235 2236.. index:: 2237 expression await 2238 expression wait 2239 launch 2240 coroutine 2241 expression type 2242 2243.. code-block:: typescript 2244 :linenos: 2245 2246 let promise = launch (): int { return 1 } () 2247 console.log(await promise) // output: 1 2248 2249If the coroutine result must be ignored, then the expression statement 2250``await`` is used. 2251 2252.. code-block:: typescript 2253 :linenos: 2254 2255 function foo() { /* do something */ } 2256 let promise = launch foo() 2257 await promise 2258 2259.. index:: 2260 coroutine 2261 expression statement await 2262 2263| 2264 2265.. _The Promise T Class: 2266 2267The Promise<T> Class 2268==================== 2269 2270.. meta: 2271 frontend_status: Partly 2272 2273The class *Promise<T>* represents the values returned by launch expressions. 2274It belongs to the essential kernel packages of the standard library 2275(see :ref:`Standard Library`) and thus imported by default and may be used 2276without any qualification. 2277 2278The following methods are used: 2279 2280- *then* takes two arguments (the first argument is the callback used if the 2281 promise is fulfilled, and the second if it is rejected), and returns 2282 *Promise<U>*. 2283 2284.. index:: 2285 class 2286 value 2287 launch expression 2288 argument 2289 callback 2290 package 2291 standard library 2292 method 2293 2294.. code-block:: typescript 2295 2296 Promise<U> Promise<T>::then<U>(fullfillCallback : 2297 function 2298 <T>(val: T) : Promise<U>, rejectCallback : (err: Object) 2299 : Promise<U>) 2300 2301- *catch* is the alias for *Promise<T>*.then<U>((value: T) : U => {}, 2302 onRejected). 2303 2304.. code-block:: typescript 2305 2306 Promise<U> Promise<T>::catch<U>(rejectCallback : (err: 2307 Object) : Promise<U>) 2308 2309- *finally* takes one argument (the callback called after *promise* is either 2310 fulfilled or rejected) and returns *Promise<T>*. 2311 2312.. index:: 2313 alias 2314 callback 2315 call 2316 2317.. code-block:: abnf 2318 2319 Promise<U> Promise<T>::finally<U>(finallyCallback : ( 2320 Object: 2321 T) : Promise<U>) 2322 2323| 2324 2325.. _Structured Coroutines: 2326 2327Structured Coroutines 2328===================== 2329 2330| 2331 2332.. _Channels Classes: 2333 2334Channels Classes 2335================ 2336 2337*Channels* are used to send data between coroutines. 2338 2339*Channels classes* are a part of the coroutine-related package of the 2340standard library (see :ref:`Standard Library`). 2341 2342.. index:: 2343 channel class 2344 coroutine 2345 package 2346 2347| 2348 2349.. _Async Functions: 2350 2351Async Functions 2352=============== 2353 2354.. meta: 2355 frontend_status: Partly 2356 2357The function *async* is implicitly a coroutine that can be called as a 2358regular function. 2359 2360The return type of an *async* function must be *Promise<T>* (see 2361:ref:`The Promise T Class`). 2362Returning values of types *Promise<T>* and *T* from the function *async* 2363is allowed. 2364 2365Using return statement without expression is allowed if the return type 2366is *Promise<void>*. 2367*No-argument* return statement can be implicitly added as the last statement 2368of the function body if there is no explicit return statement in a function 2369with the return type *Promise<void>*. 2370 2371**Note**: Using this annotation is not recommended because this type of 2372functions is only supported for the sake of backward |TS| compatibility. 2373 2374.. index:: 2375 function async 2376 coroutine 2377 return type 2378 function body 2379 backward compatibility 2380 annotation 2381 2382| 2383 2384.. _Packages: 2385 2386Packages 2387******** 2388 2389.. meta: 2390 frontend_status: Partly 2391 2392One or more *package modules* form a package. 2393 2394.. code-block:: abnf 2395 2396 packageDeclaration: 2397 packageModule+ 2398 ; 2399 2400*Packages* are stored in a file system or a database (see 2401:ref:`Compilation Units in Host System`). 2402 2403A *package* can consist of several package modules if all such modules 2404have the same *package header*. 2405 2406.. index:: 2407 package module 2408 package 2409 file system 2410 database 2411 package header 2412 2413.. code-block:: abnf 2414 2415 packageModule: 2416 packageHeader packageModuleDeclaration 2417 ; 2418 2419 packageHeader: 2420 'package' qualifiedName 2421 ; 2422 2423 packageModuleDeclaration: 2424 importDirective* packageTopDeclaration* 2425 ; 2426 2427 packageTopDeclaration: 2428 topDeclaration | packageInitializer 2429 ; 2430 2431A :index:`compile-time error` occurs if: 2432 2433- A *package module* contains no package header; or 2434 2435- Package headers of two package modules in the same package have 2436 different identifiers. 2437 2438A *package module* automatically imports all exported entities from essential 2439kernel packages of the standard library (see :ref:`Standard Library`). All 2440entities from these packages are accessible as simple names. 2441 2442A *package module* can automatically access all top-level entities 2443declared in all modules that constitute the package. 2444 2445.. index:: 2446 package module 2447 package header 2448 package 2449 identifier 2450 import 2451 exported entity 2452 access 2453 top-level entity 2454 module 2455 standard library 2456 simple name 2457 2458| 2459 2460.. _Internal Access Modifier Experimental: 2461 2462Internal Access Modifier 2463======================== 2464 2465.. meta: 2466 frontend_status: Partly 2467 2468The modifier *internal* indicates that a class member, a constructor, or 2469an interface member is accessible within its compilation unit only. 2470If the compilation unit is a package (see :ref:`Packages`), then *internal* 2471members can be used in any *package module*. If the compilation unit is a 2472separate module (see :ref:`Separate Modules`), then *internal* members can be 2473used within this module. 2474 2475.. index:: 2476 modifier 2477 internal access modifier 2478 class member 2479 constructor 2480 access 2481 package module 2482 2483.. code-block:: typescript 2484 :linenos: 2485 2486 class C { 2487 internal count: int 2488 getCount(): int { 2489 return this.count // ok 2490 } 2491 } 2492 2493 function increment(c: C) { 2494 c.count++ // ok 2495 } 2496 2497.. index:: 2498 member 2499 constructor 2500 internal modifier 2501 access 2502 2503| 2504 2505.. _Package Initializer: 2506 2507Package Initializer 2508=================== 2509 2510Among all *package modules* there can be one to contain a code that performs 2511initialization of global variables across all package modules. 2512 2513The syntax is presented below: 2514 2515.. index:: 2516 package initializer 2517 package module 2518 initialization 2519 variable 2520 2521.. code-block:: abnf 2522 2523 packageInitializer: 2524 'static' block 2525 ; 2526 2527A :index:`compile-time error` occurs if a package contains more than one 2528*package initializer*. 2529 2530A *package initializer* is executed only once right before the first activation 2531of the package (calling an exported function or accessing an exported 2532global variable). 2533 2534.. index:: 2535 package initializer 2536 package 2537 execution 2538 exported function 2539 access 2540 exported global variable 2541 function call 2542 2543| 2544 2545.. _Sub-Entity Binding: 2546 2547Sub-Entity Binding 2548================== 2549 2550The import bindings '*qualifiedName*' (that consists of at least two 2551identifiers) or '*qualifiedName* as A' bind a sub-entity to the declaration 2552scope of the current module. 2553 2554'L' is a *static* entity and the last identifier in the '*qualifiedName* A.B.L'. 2555L’s *public* access modifier is defined in the class or interface denoted in the 2556previous part of the '*qualifiedName*'. 'L' is accessible regardless of the 2557export status of the class or the interface it belongs to. 2558 2559An entity (or—in the case of overloaded methods—entities) is bound by its 2560original name, or by an alias (if an alias is set). In the latter case, the 2561original name is not accessible. 2562 2563.. index:: 2564 sub-entity binding 2565 import binding 2566 identifier 2567 module 2568 declaration scope 2569 static entity 2570 public access modifier 2571 class 2572 interface 2573 access 2574 export status 2575 entity 2576 overloaded method 2577 alias 2578 2579The following module can be considered as an example: 2580 2581.. code-block:: typescript 2582 :linenos: 2583 2584 class A { 2585 class B { 2586 public static L: int 2587 } 2588 } 2589 2590The table below illustrates the import of this module: 2591 2592+-----------------------------------+-+--------------------------------------+ 2593| Import | | Usage | 2594+===================================+=+======================================+ 2595| .. code-block:: typescript | | .. code-block:: typescript | 2596| | | | 2597| import {A.B.L} from "..." | | if (L == 0) { ... } | 2598+-----------------------------------+-+--------------------------------------+ 2599| .. code-block:: typescript | | .. code-block:: typescript | 2600| | | | 2601| import {A.B} from "..." | | let x = new B() // OK | 2602| | | let y = new A() // Error: 'A' is | 2603| | | not accessible | 2604+-----------------------------------+-+--------------------------------------+ 2605| .. code-block:: typescript | | .. code-block:: typescript | 2606| | | | 2607| import {A.B.L as X} from ".." | | if (X == 0) { ... } | 2608+-----------------------------------+-+--------------------------------------+ 2609| .. code-block:: typescript | | .. code-block:: typescript | 2610| | | | 2611| import {A.B as AB} from "..." | | let x = new AB() | 2612+-----------------------------------+-+--------------------------------------+ 2613 2614This form of binding is included in the language specifically to simplify 2615the migration from the languages that support access to sub-entities as 2616simple names. This feature is to be used only for migration. 2617 2618.. index:: 2619 import 2620 access 2621 binding 2622 migration 2623 sub-entity 2624 2625| 2626 2627.. _All Static Sub-Entities Binding: 2628 2629All Static Sub-Entities Binding 2630=============================== 2631 2632The import binding '*qualifiedName.\** ' binds all *public static* sub-entities 2633of the entity denoted by the *qualifiedName* to the declaration scope of the 2634current module. 2635 2636The following module can be considered as an example: 2637 2638.. index:: 2639 import binding 2640 static sub-entity binding 2641 public static sub-entity 2642 declaration scope 2643 entity 2644 module 2645 2646.. code-block:: typescript 2647 :linenos: 2648 2649 class A { 2650 class Point { 2651 public static X: int 2652 public static Y: int 2653 public isZero(): boolean {} 2654 } 2655 } 2656 2657The examples below illustrate the import of this module: 2658 2659.. code-block:: typescript 2660 :linenos: 2661 2662 // Import: 2663 import A.Point.* from "..." 2664 2665.. code-block:: typescript 2666 :linenos: 2667 2668 // Usage: 2669 import A.Point.* from "..." 2670 2671 if ((X == 0) && (Y == 0)) { // OK 2672 // ... 2673 } 2674 2675 let x = isZero() / Error: 'isZero' is not static 2676 2677This form of binding is included in the |LANG| language specifically to 2678simplify the migration from the languages that support access to sub-entities 2679as simple names. This feature is to be used only for migration. 2680 2681.. index:: 2682 binding 2683 migration 2684 access 2685 sub-entity 2686 simple name 2687 2688| 2689 2690.. _Import and Overloading of Function Names: 2691 2692Import and Overloading of Function Names 2693======================================== 2694 2695.. meta: 2696 frontend_status: Done 2697 2698While importing functions, the following situations can occur: 2699 2700- Different imported functions have the same name but different signatures, 2701 or a function (functions) of the current module and an imported function 2702 (functions) have the same name but different signatures. That situation 2703 is called **overloading**. 2704 2705- A function (functions) of the current module and an imported function 2706 (functions) have the same name and signature. That situation is called 2707 **shadowing**. 2708 2709.. index:: 2710 import 2711 overloading 2712 function name 2713 function 2714 imported function 2715 signature 2716 module 2717 shadowing 2718 2719| 2720 2721.. _Overloading of Function Names: 2722 2723Overloading of Function Names 2724============================= 2725 2726.. meta: 2727 frontend_status: Done 2728 2729**Overloading** is the situation when a compilation unit has access to several 2730functions with the same names (regardless of where such functions are declared). 2731The code can use all such functions if they have distinguishable signatures 2732(i.e., the functions are not override-equivalent): 2733 2734.. code-block:: typescript 2735 :linenos: 2736 2737 package P1 2738 function foo(p: int) {} 2739 2740 package P2 2741 function foo(p: string) {} 2742 2743 // Main module 2744 import * from "path_to_file_with_P1" 2745 import * from "path_to_file_with_P2" 2746 function foo (p: double) {} 2747 function main() { 2748 foo(5) // Call to P1.foo(int) 2749 foo("A string") // Call to P2.foo(string) 2750 foo(3.141592653589) // Call to local foo(double) 2751 } 2752 2753.. index:: 2754 overloading 2755 access 2756 function 2757 signature 2758 2759| 2760 2761.. _Shadowing of Function Names: 2762 2763Shadowing of Function Names 2764=========================== 2765 2766.. meta: 2767 frontend_status: Done 2768 2769**Shadowing** is the :index:`compile-time error` that occurs if an imported 2770function is identical to the function declared in the current compilation 2771unit (the same names and override-equivalent signatures), i.e., the 2772declarations are duplicated. 2773 2774Qualified import or alias in import can be used to access the imported entity. 2775 2776.. code-block:: typescript 2777 :linenos: 2778 2779 package P1 2780 function foo() {} 2781 package P2 2782 function foo() {} 2783 // Main program 2784 import * from "path_to_file_with_P1" 2785 import * from "path_to_file_with_P2" /* Error: duplicating 2786 declarations imported*/ 2787 function foo() {} /* Error: duplicating declaration identified 2788 */ 2789 function main() { 2790 foo() // Error: ambiguous function call 2791 // But not a call to local foo() 2792 // foo() from P1 and foo() from P2 are not accessible 2793 } 2794 2795.. index:: 2796 shadowing 2797 function name 2798 imported function 2799 compilation unit 2800 override-equivalent signature 2801 qualified import 2802 alias 2803 import 2804 access 2805 imported entity 2806 2807| 2808 2809.. _Generics Declaration-Site Variance: 2810 2811Generics: Declaration-Site Variance 2812*********************************** 2813 2814Optionally, a type parameter can have keywords ``in`` or ``out`` (a 2815*variance modifier*, which specifies the variance of the type parameter). 2816 2817**NOTE**: This description of variance modifiers is preliminary. The details 2818are to be specified in the future versions of the |LANG| language. 2819 2820Type parameters with the keyword ``out`` are *covariant*, and can be used in 2821the out-position only. 2822 2823Type parameters with the keyword ``in`` are *contravariant*, and can be used 2824in the in-position only. 2825 2826Type parameters with no variance modifier are implicitly *invariant*, and can 2827occur in any position. 2828 2829.. index:: 2830 generic 2831 declaration-site variance 2832 type parameter 2833 keyword in 2834 keyword out 2835 variance modifier 2836 variance modifier 2837 in-position 2838 out-position 2839 2840A :index:`compile-time error` occurs if a function, method, or constructor 2841type parameters have a variance modifier specified. 2842 2843*Variance* is used to describe the subtyping (see :ref:`Subtyping`) operation 2844on parameterized types (see :ref:`Generic Declarations`). The 2845variance of the corresponding type parameter *F* defines the subtyping between 2846*T<A>* and *T<B>* (in the case of declaration-site variance with two different 2847types *A* <: *B*) as follows: 2848 2849- Covariant (*out F*): *T<A>* <: *T<B>*; 2850- Contravariant (*in F*): *T<A>* :> *T<B>*; 2851- Invariant (default) (*F*). 2852 2853.. index:: 2854 type parameter 2855 variance modifier 2856 function 2857 method 2858 constructor 2859 variance 2860 covariance 2861 contravariance 2862 invariance 2863 type-parameterized declaration 2864 parameterized type 2865 subtyping 2866 declaration-site variance 2867 2868.. raw:: pdf 2869 2870 PageBreak 2871 2872 2873