Lesson 8

Datatyping and casting

Now we come to something, which we are already kind of familiar with, datatyping. In AS3 the rules are very strict regarding datatyping. What is meant is that the type of each variable once declared has to be defined and the variable will maintain this datatype. A datatype is for example String or Number or TextField etc. If we have a textfield and want to display a number we cannot just do so, since a number is not a string. Only when we convert the number to a string we can display it in the textfield. The reason is that textfields will only display strings. If we do otherwise we will get an error. The example below shows that.

We are already familiar with this example. To convert a value with one datatype to another we just put the value in parenthesis and write the datatype, to which we want to convert the value, in the front as shown in the example. Both variables will show the same value. The difference is one of them is a string and the other a number.

package 
{
	import flash.display.Sprite;
	import flash.text.TextField;
	public class Starter_11 extends Sprite 
	{
	       private var tField:TextField;
	       public function Starter_11 () 
	       {
	               myTest();
	       }
	       private function myTest():void 
	       {
	               var a:Testvar = new Testvar ();
	               tField = new TextField();
	               tField.text = a.test;
	               trace(a.num_test);
	               addChild(tField);
	       }
	}
}
//
import flash.display.Sprite;
class Testvar extends Sprite 
{
	public var test:String;
	public function Testvar() 
	{
	       test = String(2000); // datatype conversion
	}
}

We can convert further if we need to as shown in the following example:

import flash.display.Sprite;
class Testvar extends Sprite 
{
	public var test:String;
	public var num_test:uint;
	public function Testvar() 
	{
	   test = String(2000);
	   num_test = uint(test);
	}
}

Next I will introduce the getter and setter.

previous  next