1 /* 2 * Copyright (C) 2018 The Dagger Authors. 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 17 package dagger.internal.codegen; 18 19 import static com.google.common.collect.Iterables.getOnlyElement; 20 import static dagger.internal.codegen.BindingRequest.bindingRequest; 21 22 import com.squareup.javapoet.CodeBlock; 23 import dagger.internal.codegen.FrameworkFieldInitializer.FrameworkInstanceCreationExpression; 24 25 /** 26 * A {@link FrameworkInstanceCreationExpression} for {@link dagger.model.BindingKind#OPTIONAL 27 * optional bindings}. 28 */ 29 final class OptionalFactoryInstanceCreationExpression 30 implements FrameworkInstanceCreationExpression { 31 private final OptionalFactories optionalFactories; 32 private final ContributionBinding binding; 33 private final ComponentImplementation componentImplementation; 34 private final ComponentBindingExpressions componentBindingExpressions; 35 OptionalFactoryInstanceCreationExpression( OptionalFactories optionalFactories, ContributionBinding binding, ComponentImplementation componentImplementation, ComponentBindingExpressions componentBindingExpressions)36 OptionalFactoryInstanceCreationExpression( 37 OptionalFactories optionalFactories, 38 ContributionBinding binding, 39 ComponentImplementation componentImplementation, 40 ComponentBindingExpressions componentBindingExpressions) { 41 this.optionalFactories = optionalFactories; 42 this.binding = binding; 43 this.componentImplementation = componentImplementation; 44 this.componentBindingExpressions = componentBindingExpressions; 45 } 46 47 @Override creationExpression()48 public CodeBlock creationExpression() { 49 return binding.dependencies().isEmpty() 50 ? optionalFactories.absentOptionalProvider(binding) 51 : optionalFactories.presentOptionalFactory( 52 binding, 53 componentBindingExpressions 54 .getDependencyExpression( 55 bindingRequest( 56 getOnlyElement(binding.dependencies()).key(), binding.frameworkType()), 57 componentImplementation.name()) 58 .codeBlock()); 59 } 60 61 @Override useInnerSwitchingProvider()62 public boolean useInnerSwitchingProvider() { 63 // Share providers for empty optionals from OptionalFactories so we don't have numerous 64 // switch cases that all return Optional.empty(). 65 return !binding.dependencies().isEmpty(); 66 } 67 } 68