6

I have an Application class that I want to be different in each build variant like debug and release.
this is my map:

app/      
   |      
   |----debug/          
             |----java\            
                       |----com.example.App.class       
             |----res\
                      |----mipmap-hdpi       
   |----main/          
             |----java\      
                      |----com.example.App.class       
             |----res\
                      |----mipmap-hdpi            

but in android studio give me this error message "duplicate class found in ..."
but it does not show any error in my resources.
my question is why gradle cannot figure it out what class should use in different build variant but it can decide what resource must be used in different build variants.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
max
  • 5,963
  • 12
  • 49
  • 80
  • Instead of using same class twice, why not configure the `BuildConfig` class in `build.gradle` ? – Debdeep Feb 03 '18 at 08:23
  • a little more explanation, please. – max Feb 03 '18 at 08:30
  • I guess you're referring to the `App.class` twice under `buildTypes` for achieving different functionalities? – Debdeep Feb 03 '18 at 08:34
  • yes its what I want to do – max Feb 03 '18 at 08:52
  • place an `if(BuildConfig.debug)` and else condition for every code that depends on build types in your `main` else follow the correct approach that has been answered by @laalto below. – Debdeep Feb 03 '18 at 09:33
  • yes but the problem is that I have dependency with debugImplementation and I don't have that dependency on the release so I have to make it comment and uncomment every time I want to change build variant. – max Feb 03 '18 at 09:49

1 Answers1

9

Code under main is shared between all build types. Hence the class is there twice, once from debug and again from main.

To have build type specific source files, put them under build type specific folders instead of main. For example if you have the usual debug and release build types, put the other variant under release.

Why this is not needed for resources is because resource merging can override resources over build types. There is no code merging.

laalto
  • 150,114
  • 66
  • 286
  • 303