1 /*
2  * Copyright (C) 2014 Google, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package dagger.internal.codegen.writer;
17 
18 import com.google.common.base.Function;
19 import com.google.common.base.Optional;
20 import com.google.common.collect.FluentIterable;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.Iterables;
23 import java.io.IOException;
24 import java.util.Set;
25 
26 public final class FieldWriter extends VariableWriter {
27   private Optional<Snippet> initializer;
28 
FieldWriter(TypeName type, String name)29   FieldWriter(TypeName type, String name) {
30     super(type, name);
31     this.initializer = Optional.absent();
32   }
33 
setInitializer(Snippet initializer)34   public void setInitializer(Snippet initializer) {
35     this.initializer = Optional.of(initializer);
36   }
37 
setInitializer(String initializer, Object... args)38   public void setInitializer(String initializer, Object... args) {
39     this.initializer = Optional.of(Snippet.format(initializer, args));
40   }
41 
42   @Override
write(Appendable appendable, Context context)43   public Appendable write(Appendable appendable, Context context) throws IOException {
44     super.write(appendable, context);
45     if (initializer.isPresent()) {
46       appendable.append(" = ");
47       initializer.get().write(appendable, context);
48     }
49     appendable.append(';');
50     return appendable;
51   }
52 
53   @Override
referencedClasses()54   public Set<ClassName> referencedClasses() {
55     Iterable<? extends HasClassReferences> concat =
56         Iterables.concat(ImmutableList.of(type()), initializer.asSet(), annotations);
57     return FluentIterable.from(concat)
58         .transformAndConcat(new Function<HasClassReferences, Set<ClassName>>() {
59           @Override
60           public Set<ClassName> apply(HasClassReferences input) {
61             return input.referencedClasses();
62           }
63         })
64         .toSet();
65   }
66 }
67