0

I know the difference between the two as discussed here.

As Android developer,

  1. Why I should care about this?
  2. In gradle, why should I use compileOnly vs implementation/api?
user1506104
  • 6,554
  • 4
  • 71
  • 89

1 Answers1

1

Why I should care about this?

To make your apps build but not ship with unnecessary stuff.

In gradle, why should I use compileOnly vs implementation/api?

The documentation for compileOnly gives one use case as an example:

Gradle adds the dependency to the compilation classpath only (it is not added to the build output). This is useful when you're creating an Android library module and you need the dependency during compilation, but it's optional to have present at runtime. That is, if you use this configuration, then your library module must include a runtime condition to check whether the dependency is available, and then gracefully change its behavior so it can still function if it's not provided. This helps reduce the size of the final APK by not adding transient dependencies that aren't critical. This configuration behaves just like provided (which is now deprecated).

source

For example, consider a push messaging library that supports both Firebase FCM and Amazon ADM but does not require either. It would unnecessarily bloat apps if it would ship with both as transitive dependencies. With compileOnly the library can still be built. Developers using the library can select which dependencies to actually use.

Another example could be compile-time annotations that do not need to ship with the application.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • Thanks @laalto. Could you please share an instance where "you need the dependency during compilation, but it's optional to have present at runtime." – user1506104 Aug 01 '18 at 09:40
  • Edited to add an example – laalto Aug 01 '18 at 09:45
  • This is the answer I am looking for. I will accept your answer. One more thing, if i am one of the developers using the library, how can I declare in my app that I want to use FCM (or ADM or other dependency that used compileOnly) with the library? Declaring "implementation 'com.google.firebase:firebase-core:16.0.1'" is enough? – user1506104 Aug 01 '18 at 10:01
  • That depends how the library is being built i.e. what mechanism it actually uses for determining which optional features to enable. The build tooling is just an enabler. – laalto Aug 01 '18 at 10:04