1/* 2 * Copyright (c) 2023 - 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 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16let a = 0; 17 18function foo(): int { 19 a++; 20 return 1; 21} 22 23function bar(): int { 24 a++; 25 return 2; 26} 27 28class Residence { 29 numberOfRooms: int = 1; 30} 31 32class Person { 33 residence: Residence = new Residence(); 34} 35 36function aux(): Person | null { 37 return null; 38} 39 40function main(): void { 41 a = 0; 42 let test = false; 43 let john: Person | null = aux(); 44 45 try { 46 let residence = (john as Person).residence; 47 } catch (e: ClassCastError) { 48 test = true; 49 } 50 assert(test == true); 51 52 test = false; 53 assert(test == false); 54 55 try { 56 let numbers: int = john!.residence.numberOfRooms; 57 } catch (e: NullPointerError) { 58 test = true; 59 } 60 assert(test == true); 61 62 test = false; 63 assert(test == false); 64 try { 65 let numbers: int = foo() + bar() + john!.residence.numberOfRooms; 66 } catch (e: NullPointerError) { 67 test = true; 68 } 69 assert(test == true); 70 assert(a == 2); // foo and bar were evaluated 71 72 john = new Person(); 73 74 let numbers: int = john.residence.numberOfRooms; 75 assert(numbers == 1); 76 77 numbers = foo() + bar() + john.residence.numberOfRooms; 78 assert(numbers == 4); 79} 80