Gradle中各种写依赖的方式有什么区别?

Kev*_*nle 1 android android-gradle-plugin

我已经看到以下在 Gradle 中编写依赖项的不同方式:

implementation("com.squareup.okhttp3:okhttp:3.12.0")
Run Code Online (Sandbox Code Playgroud)

implementation 'com.squareup.okhttp3:okhttp:3.12.0'
Run Code Online (Sandbox Code Playgroud)

compile 'com.squareup.okhttp3:okhttp:3.12.0'
Run Code Online (Sandbox Code Playgroud)

它们是完成同一件事的不同方式还是它们之间存在差异?

Pel*_*cho 5

build.gradle文件只是Groovy脚本。所以它的语法在这里适用

在 Groovy 中,您可以在调用函数时忽略括号,以便

implementation 'com.squareup.okhttp3:okhttp:3.12.0'
Run Code Online (Sandbox Code Playgroud)

实际上相当于

implementation('com.squareup.okhttp3:okhttp:3.12.0')
Run Code Online (Sandbox Code Playgroud)

在 Groovy 中,您还有GStrings,它们由". 它们包含嵌入的Strings。在这种特殊情况下,您没有插入任何值,因此两者

implementation 'com.squareup.okhttp3:okhttp:3.12.0'
Run Code Online (Sandbox Code Playgroud)

implementation "com.squareup.okhttp3:okhttp:3.12.0"
Run Code Online (Sandbox Code Playgroud)

是等价的。请注意,如果您想插入一些值,您会这样做

implementation "com.squareup.okhttp3:okhttp:$okhttpVersion" // this line works
implementation 'com.squareup.okhttp3:okhttp:$okhttpVersion' // this line doesn't work
Run Code Online (Sandbox Code Playgroud)

compile不推荐使用implementation和定义依赖项的方法api。您可以在此处找到更多信息。您可以考虑,如果您以某种方式公开您将使用的依赖项的类,api但如果您在内部使用依赖项implementation就可以了