6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Haxeで読みこみ専用、書きこみ専用の変数とプロパティ

Last updated at Posted at 2012-12-26

Haxeでは読み込み専用の変数、書き込み専用の変数を簡単に設定することができます。

#読み込み専用

Main.hx
class Main {
	//読み込み時はどこからでも出来ますが、書き込みはMainからのみになります。
	static public var readOnly(default, null):Int;
	
	static function main() {
		var i = Main.readOnly;		//ok
		Main.readOnly = 1; 			//ok
		
		Test1.test();
	}
}

class Test1 {
	static public function test() {
		var i = Main.readOnly;		//ok
		Main.readOnly = 1; 			//error
	}
}

#書きこみ専用

Main.hx
class Main {
	//書き込みはどこからでも出来ますが、読み込みはMainからのみになります。
	static public var writeOnly(null, default):Int;
	
	static function main() {
		var i = Main.writeOnly;		//ok
		Main.writeOnly = 1; 		//ok
		
		Test1.test();
	}
}

class Test1 {
	static public function test() {
		var i = Main.writeOnly;		//error
		Main.writeOnly = 1; 		//ok
	}
}

いちいちsetter,getterを書かなくていいので、楽ですね。
もちろん、setter,getterを書くこともできます。

#getter,setter(プロパティ)

Haxe3:

Main.hx
class Main {   
	static public var x(get,set):Int;
	static public var y(get, never):Int;
	static public var z(default, set):Int;	
	
	static function get_x():Int		 	{ 
		trace( "get_x" );
		return x;		//setter内ではget_xは呼ばれない。
	}
	static function set_x(v:Int):Int {
		trace( "set_x" );
		return x = v;	//setter内ではget_x,set_xは呼ばれない。
	}
	
	static function get_y():Int			{ 
		trace( "get_y" );
		return 1; 
	}

	static function set_z(v:Int):Int	{ 
		trace( "set_z" );
		return z = v; 	//setter内ではset_zは呼ばれない。
	}
	
	static function main() {
		var i:Int;
		i = x;	//get_x
		x = 1;	//set_x
		i = y;	//get_y
		y = 1;	//error
		i = z;	//i = z;
		z = 1;	//set_z
	}
}

Haxe2:

Main.hx
class Main {   
	static public var x(getX,setX):Int;
	static public var y(getY, never):Int;
	static public var z(default, setZ):Int;	
	
	static function getX():Int		 	{ 
		trace( "getX" );
		return x;		//setter内ではgetXは呼ばれない。
	}
	static function setX(v:Int):Int {
		trace( "setX" );
		return x = v;	//setter内ではgetX,setXは呼ばれない。
	}
	
	static function getY():Int			{ 
		trace( "getY" );
		return 1; 
	}
	static function setZ(v:Int):Int	{ 
		trace( "setZ" );
		return z = v; 	//setter内ではsetZは呼ばれない。
	}
	
	static function main() {
		var i:Int;
		i = x;	//getX
		x = 1;	//setX
		i = y;	//getY
		y = 1;	//error
		i = z;	//i = z;
		z = 1;	//setZ
	}
}
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?