LoginSignup
0
0

More than 5 years have passed since last update.

Haxeの@:callableメタデータを雑に理解した。

Posted at

@:callableとは

issueによると
Haxe3.2から追加されたメタデータで、abstractを呼び出し可能にできるみたいです。
ユニットテストを見ていると、

@:callable
abstract A<T>(T) from T {}

class Main {
  public static function main() {
    var func:A<Int->Int> = function(x:Int) return x * 2;
    func()
  }
}

のように使うみたいです。
ただ、これだけだと普通のクロージャを呼び出すのと変わりように思えますが、ちょっとトリッキーなことができます。

演算子をオーバーロードする

下のような書き方をすると、演算子をオーバーロードすることができます。
呼び出し演算子はオーバーロードできないみたいですね。


@:callable
abstract TestFunc(haxe.Constraints.Function) from haxe.Constraints.Function {
    @:op(A * B) public function multiply(right:Int) {
        return 2 * right;
    }

}


class Main {

    public static function main() {
        var a:TestFunc = function() {
            return "Hello!";
        };
        trace(a * 10); // 20
        a(); // Hello"
    }

}

あと、@:arrayAccessメタデータを使えば配列っぽくアクセスすることもできるみたいです。

演算子がオーバーロードできたから何が嬉しいんだ、みたいなところはまだわかってないのですが、
とりあえず@:callableの使い方を雑に理解した話でした。

どなたか良い活用法を知っているからがいらっしゃれば教えてください...

0
0
1

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
0
0