LoginSignup
0
0

More than 5 years have passed since last update.

同一のフィールドを持つインスタンスがコレクション内に入っていた場合の特殊(?)なアクセス

Last updated at Posted at 2015-10-29

少しはまったのでメモ。
Groovyでは、コレクション内のインスタンスが同一のフィールドを持っていた場合、(コレクション).(フィールド)でアクセスできる。下の例のように、collectの簡易表現になりうる。

inner.groovy
class A {
    List inner = []
}

class B {
    List inner = []
    Map inner_map = [:]
}

class C {
    List different_inner = []
}

def a1 = new A()
def a2 = new A()
def b1 = new B()
def c1 = new C()

a1.inner.add(1)
a1.inner.add(2)
a2.inner.add(3)
a2.inner.add(4)
b1.inner.add(5)
c1.different_inner.add(6)

def outer = [a1, a2, b1]
println(outer.inner)
// >> [[1, 2], [3, 4], [5]]
// 同一表現?
println(outer.collect {
  it.inner
})
// >> [[1, 2], [3, 4], [5]]

outer.add(c1)
println(outer.inner)
// >> groovy.lang.MissingPropertyException
0
0
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
0
0