Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 8. Datatypes and Type Checking > Warnings for Missing Type Annotations - Pg. 144

Next, consider the following code which defines a variable, b , of type Boolean, and assigns b an integer value, 5: var b:Boolean = 5; Even though the value 5 does not belong to the Boolean datatype, the compiler does not generate a type mismatch error. Instead, it assumes that the programmer wishes to convert the value 5 to the Boolean datatype (according to the rules described in the later section "Conversion to Primitive Types") and issues a warning to that effect. This lenience can cut down on the amount of code in a program. For example, sup- pose the VirtualPet class's getHunger( ) method's return type were declared as Number. A program could then create a variable indicating whether a pet is alive or dead using the following code: var isAlive:Boolean = somePet.getHunger( ); According to the rules described in the section "Conversion to Primitive Types," the number 0 converts to the value false , while all other numbers convert to the value true . Hence, if getHunger( ) returns anything other than 0, isAlive is set to true ; oth- erwise, isAlive is set to false (the pet is dead when it has no calories left). For comparison, here's the alternative, slightly longer code that would be necessary if the compiler enforced type checking for variables of type Boolean (rather than allow- ing a runtime conversion): var isAlive:Boolean = somePet.getHunger( ) > 0;