From faeaff225fc9a1332abfefc4b45cfb55b7569e2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BAlio=20Hoffimann?= Date: Tue, 14 Jul 2020 22:03:40 -0300 Subject: [PATCH] Add getproperty method --- src/composition.jl | 26 +++++++++++++++----------- test/compositions.jl | 6 ++++++ 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/composition.jl b/src/composition.jl index 4d96d33..8d87575 100644 --- a/src/composition.jl +++ b/src/composition.jl @@ -102,17 +102,21 @@ Names of parts in the composition `c`. """ names(c::Composition{D,SYMS}) where {D,SYMS} = SYMS -# """ -# getproperty(c, name) -# -# Return the value of part with given `name` in the composition `c`. -# """ -# function getproperty(c::Composition{D,SYMS}, S::Symbol) where {D,SYMS} -# for (i, SYM) in enumerate(SYMS) -# S == SYM && (return c.parts[i]) -# end -# @error "invalid part $S" -# end +""" + getproperty(c, name) + +Return the value of part with given `name` in the composition `c`. +""" +function getproperty(c::Composition{D,SYMS}, S::Symbol) where {D,SYMS} + if S == :parts + getfield(c, :parts) + else + for (i, SYM) in enumerate(SYMS) + S == SYM && (return c.parts[i]) + end + @error "invalid part name '$S'" + end +end # ------------ # IO methods diff --git a/test/compositions.jl b/test/compositions.jl index 20b3002..e551932 100644 --- a/test/compositions.jl +++ b/test/compositions.jl @@ -14,4 +14,10 @@ @test names(-c) == names(c) @test names(c - c) == names(c) @test names(2c) == names(c) + + # get part by name + c = Composition(a=3,b=2,c=1) + @test c.a == 3 + @test c.b == 2 + @test c.c == 1 end