5
5

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.

[Groovy]traitを使って無理やりお手軽ダックタイピング

Posted at

概要

クラス宣言時にimplementsを使って、クラスにtraitを組み込むことができますが、クラス生成時(new)にasキーワードを使うことで、そのオブジェクトに対してtraitを組み込むことができます。

サンプルソース

class A {
    def doSomething() {
        "This is Class A"
    }
}

class B {
    def greeting() {
        "This is Class B"
    }
}


def exec( def obj ) {
    "${obj.doSomething()} - executed!"
}

実行してみる

以下のコードは当然問題なく実行できます。

def a = new A()
assert exec(a) == "This is Class A - executed!"

以下は当然エラーになります。

// execメソッドは、渡されたオブジェクトのdoSomething()を実行するので、
// 今回渡しているBクラスにはそんなメソッドは無いので当然エラーになる。
def b = new B()
assert exec(b) == "This is Class B - executed!"

クラスを全くいじらずにこの問題を解決する

そこで、Groovy2.3から利用できるtraitの出番です。
traitとasキーワードを使って、このクラスBにdoSomethingメソッドを動的に追加してあげることがでます。

trait Wrapper {
    def doSomething() {
        greeting()
    }
}

def b = new B() as Wrapper
assert exec(b) == "This is Class B - executed!"
assert b.greeting() == "This is Class B"

この使い方が実用的か、問題ないかは置いておいて、こんなことができますよ、ということです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?