Android kotlin dsl gradle

Setting up Gradle with Kotlin DSL, a simple guide

Kotlin is a very a pretty nice adoptive language and user friendly. It really replaced Java from my everyday programming. However, it was not enough. We all know that groovy runs on JVM. So, why do I even need a new language just for my builds? Can’t it be Java? So Java is the basic language for the JVM, Kotlin runs on JVM, Groovy runs on JVM and my build system has a separated language from my business logic system. Why?

I was introduced to Gradle with Kotlin accidentally. I never heard of Kotlin DSL in terms of Gradle. I just created a new Spring project and the built file looked kind of strange. After a little Google-ing, everything was clear. Long story short, I removed groovy from my Gradle build tool in my Android project, and replaced it with Kotlin. It shouldn’t take more than 15 minutes to do this, but you can struggle with some things in particular.

Here are some things to know:

Start with the simplest thing ever: rename your settings.gradle to settings.gradle.kts. It should have less than 5 lines of code:

is just going to be:

Than stick with build.gradle project level. It’s shorter (or it has repetitive things). So instead of having a build.gradle just rename the file to build.gradle.kts. There are 2 important things to note here (at least in my case).

If you need a variable which is going to be shared across modules and be kept in project level gradle, the

And then you can access it by doing this:

in your app module.

The custom Clean Task, transforms from:

Don’t forget that Kotlin has no idea what ‘ ‘ are. Use » » instead. Also, the classpaths, are just becoming simple Kotlin methods with String parameters. So here is my full build.gradle.kts:

So now let’s jump to build.gradle module app. I could just paste the whole file (which I would do below), but there are some things to note. For example variables. I know that I it sounds a little stupid, but I never bothered writing variables in groovy. It was better with just copy-pasting the version 🤦‍♂️. With Kotlin, it’s a little more natural to write variables.

Now the plugins transform:

Note that when you have kotlin specific plugins you can just use kotlin() method, otherwise stick to id(). The defaultConfig becomes from:

The buildTypes clause has also a new thing. Instead of:

A now a tricky little thing, KotlinOptions. You would need a getTask() method to access it. So this:

The rest is just the same. I’m just pasting the full build.gradle.kts (module app) whole file in case I forgot to mention something. There is also a nice guide here in case you have more unmentioned trouble around.

Conclusion
Unfortunately, I am still unable to tell the difference of the build speed because my project is still small. However, I might share it later on my twitter.

Источник

Gradle

In order to build a Kotlin project with Gradle, you should apply the Kotlin Gradle plugin to your project and configure the dependencies.

Plugin and versions

Apply the Kotlin Gradle plugin by using the Gradle plugins DSL.

The Kotlin Gradle plugin and the kotlin-multiplatform plugin 1.6.0 require Gradle 6.1 or later.

The placeholder should be replaced with the name of one of the plugins that will be discussed in subsequent sections.

Targeting multiple platforms

Projects targeting multiple platforms, called multiplatform projects, require the kotlin-multiplatform plugin. Learn more about the plugin.

The kotlin-multiplatform plugin works with Gradle 6.1 or later.

Targeting the JVM

To target the JVM, apply the Kotlin JVM plugin.

The version should be literal in this block, and it cannot be applied from another build script.

Alternatively, you can use the older apply plugin approach:

Applying Kotlin plugins with apply in the Kotlin Gradle DSL is not recommended – see why.

Kotlin and Java sources

Kotlin sources and Java sources can be stored in the same folder, or they can be placed in different folders. The default convention is to use different folders:

The corresponding sourceSets property should be updated if you are not using the default convention:

Читайте также:  Disk usage pro android

In the build module, you may have related compile tasks, for example:

compileKotlin and compileJava

compileTestKotlin and compileTestJava

main and test source set compile tasks are not related.

For such related tasks, the Kotlin Gradle plugin checks for JVM target compatibility. Different values of jvmTarget in the kotlin extension and targetCompatibility in the java extension cause incompatibility. For example: the compileKotlin task has jvmTarget=1.8 , and the compileJava task has (or inherits) targetCompatibility=15 .

Control the behavior of this check by setting the kotlin.jvm.target.validation.mode property in the build.gradle file equal to:

warning – the default value; the Kotlin Gradle plugin will print a warning message.

error – the plugin will fail the build.

ignore – the plugin will skip the check and won’t produce any messages.

Set custom JDK home

By default, Kotlin compile tasks use the current Gradle JDK. If you need to change the JDK by some reason, you can set the JDK home in the following ways:

For Gradle 6.7 and later – with Java toolchains or the Task DSL to set a local JDK.

For earlier Gradle versions without Java toolchains (up to 6.6) – with the UsesKotlinJavaToolchain interface and the Task DSL.

The jdkHome compiler option is deprecated since Kotlin 1.5.30.

When you use a custom JDK, note that kapt task workers use process isolation mode only, and ignore the kapt.workers.isolation property.

Gradle Java toolchains support

Gradle 6.7 introduced Java toolchains support. Using this feature, you can:

Use a JDK and a JRE that are different from the Gradle ones to run compilations, tests, and executables.

Compile and test code with a not-yet-released language version.

With toolchains support, Gradle can autodetect local JDKs and install missing JDKs that Gradle requires for the build. Now Gradle itself can run on any JDK and still reuse the remote build cache feature for tasks that depend on a major JDK version.

The Kotlin Gradle plugin supports Java toolchains for Kotlin/JVM compilation tasks. JS and Native tasks don’t use toolchains. The Kotlin compiler always uses the JDK the Gradle daemon is running on. A Java toolchain:

Sets the jdkHome option available for JVM targets.

Sets the kotlinOptions.jvmTarget to the toolchain’s JDK version if the user doesn’t set the jvmTarget option explicitly. If the user doesn’t configure the toolchain, the jvmTarget field will use the default value. Learn more about JVM target compatibility.

Affects which JDK kapt workers are running on.

Use the following code to set a toolchain. Replace the placeholder with the JDK version you would like to use:

Note that setting a toolchain via the kotlin extension will update the toolchain for Java compile tasks as well.

You can set a toolchain via the java extension, and Kotlin compilation tasks will use it:

To set any JDK (even local) for the specific task, use the Task DSL.

Setting JDK version with the Task DSL

If you use the a Gradle version earlier than 6.7, there is no Java toolchains support. You can use the Task DSL that allows setting any JDK version for any task implementing the UsesKotlinJavaToolchain interface. At the moment, these tasks are KotlinCompile and KaptTask . If you want Gradle to search for the major JDK version, replace the placeholder in your build script:

Or you can specify the path to your local JDK and replace the placeholder with this JDK version:

Targeting JavaScript

When targeting only JavaScript, use the kotlin-js plugin. Learn more

Kotlin and Java sources for JavaScript

This plugin only works for Kotlin files, so it is recommended that you keep Kotlin and Java files separate (if the project contains Java files). If you don’t store them separately, specify the source folder in the sourceSets block:

Targeting Android

It’s recommended to use Android Studio for creating Android applications. Learn how to use Android Gradle plugin.

Configuring dependencies

To add a dependency on a library, set the dependency of the required type (for example, implementation ) in the dependencies block of the source sets DSL.

Dependency types

Choose the dependency type based on your requirements.

Used both during compilation and at runtime and is exported to library consumers.

If any type from a dependency is used in the public API of the current module, use an api dependency.

Used during compilation and at runtime for the current module, but is not exposed for compilation of other modules depending on the one with the `implementation` dependency.

Use for dependencies needed for the internal logic of a module.

If a module is an endpoint application which is not published, use implementation dependencies instead of api dependencies.

Used for compilation of the current module and is not available at runtime nor during compilation of other modules.

Use for APIs which have a third-party implementation available at runtime.

Available at runtime but is not visible during compilation of any module.

Читайте также:  Проверка имей андроид команда

Dependency on the standard library

A dependency on the standard library ( stdlib ) is added automatically to each source set. The version of the standard library used is the same as the version of the Kotlin Gradle plugin.

For platform-specific source sets, the corresponding platform-specific variant of the library is used, while a common standard library is added to the rest. The Kotlin Gradle plugin will select the appropriate JVM standard library depending on the kotlinOptions.jvmTarget compiler option of your Gradle build script.

If you declare a standard library dependency explicitly (for example, if you need a different version), the Kotlin Gradle plugin won’t override it or add a second standard library.

If you do not need a standard library at all, you can add the opt-out option to the gradle.properties :

Set dependencies on test libraries

The kotlin.test API is available for testing Kotlin projects on all supported platforms. Add the dependency kotlin-test to the commonTest source set, and the Gradle plugin will infer the corresponding test dependencies for each test source set:

kotlin-test-common and kotlin-test-annotations-common for common source sets

kotlin-test-junit for JVM source sets

kotlin-test-js for Kotlin/JS source sets

Kotlin/Native targets do not require additional test dependencies, and the kotlin.test API implementations are built-in.

You can use shorthand for a dependency on a Kotlin module, for example, kotlin(«test») for «org.jetbrains.kotlin:kotlin-test».

You can use the kotlin-test dependency in any shared or platform-specific source set as well.

For Kotlin/JVM, Gradle uses JUnit 4 by default. Therefore, the kotlin(«test») dependency resolves to the variant for JUnit 4, namely kotlin-test-junit .

You can choose JUnit 5 or TestNG by calling useJUnitPlatform() or useTestNG() in the test task of your build script. The following example is for an MPP project:

The following example is for a JVM project:

If you need to use a different JVM test framework, disable automatic testing framework selection by adding the line kotlin.test.infer.jvm.variant=false to the project’s gradle.properties file. After doing this, add the framework as a Gradle dependency.

If you had used a variant of kotlin(«test») in your build script explicitly and project build stopped working with a compatibility conflict, see this issue in the Compatibility Guide.

Set a dependency on a kotlinx library

If you use a kotlinx library and need a platform-specific dependency, you can use platform-specific variants of libraries with suffixes such as -jvm or -js , for example, kotlinx-coroutines-core-jvm . You can also use the library’s base artifact name instead – kotlinx-coroutines-core .

If you use a multiplatform library and need to depend on the shared code, set the dependency only once, in the shared source set. Use the library’s base artifact name, such as kotlinx-coroutines-core or ktor-client-core .

Set dependencies at the top level

Alternatively, you can specify the dependencies at the top level, using the following pattern for the configuration names: . This can be helpful for some Gradle built-in dependencies, like gradleApi() , localGroovy() , or gradleTestKit() , which are not available in the source sets’ dependency DSL.

Annotation processing

Kotlin supports annotation processing via the Kotlin annotation processing tool kapt .

Incremental compilation

The Kotlin Gradle plugin supports incremental compilation. Incremental compilation tracks changes to source files between builds so only files affected by these changes are compiled.

Incremental compilation is supported for Kotlin/JVM and Kotlin/JS projects and is enabled by default.

There are several ways to switch off incremental compilation:

kotlin.incremental=false for Kotlin/JVM.

kotlin.incremental.js=false for Kotlin/JS projects.

Use -Pkotlin.incremental=false or -Pkotlin.incremental.js=false as a command line parameter.

The parameter should be added to each subsequent build, and any build with incremental compilation disabled invalidates incremental caches.

The first build is never incremental.

Gradle build cache support

The Kotlin plugin uses the Gradle build cache, which stores the build outputs for reuse in future builds.

To disable caching for all Kotlin tasks, set the system property flag kotlin.caching.enabled to false (run the build with the argument -Dkotlin.caching.enabled=false ).

If you use kapt, note that kapt annotation processing tasks are not cached by default. However, you can enable caching for them manually.

Gradle configuration cache support

The configuration cache is available in Gradle 6.5 and later as an experimental feature. You can check the Gradle releases page to see whether it has been promoted to stable.

The Kotlin plugin uses the Gradle configuration cache, which speeds up the build process by reusing the results of the configuration phase.

See the Gradle documentation to learn how to enable the configuration cache. After you enable this feature, the Kotlin Gradle plugin will automatically start using it.

Compiler options

Use the kotlinOptions property of a Kotlin compilation task to specify additional compilation options.

When targeting the JVM, the tasks are called compileKotlin for production code and compileTestKotlin for test code. The tasks for custom source sets are named according to their compile Kotlin patterns.

The names of the tasks in Android Projects contain build variant names and follow the compile Kotlin pattern, for example, compileDebugKotlin or compileReleaseUnitTestKotlin .

When targeting JavaScript, the tasks are called compileKotlinJs for production code and compileTestKotlinJs for test code, and compile KotlinJs for custom source sets.

Читайте также:  Ios безопаснее чем android

To configure a single task, use its name. Examples:

Note that with the Gradle Kotlin DSL, you should get the task from the project’s tasks first.

Use the Kotlin2JsCompile and KotlinCompileCommon types for JS and common targets, respectively.

It is also possible to configure all of the Kotlin compilation tasks in the project:

Here is a complete list of options for Gradle tasks:

Attributes common to JVM, JS, and JS DCE

Report an error if there are any warnings

Don’t generate warnings

Enable verbose logging output. Works only when the Gradle debug log level enabled

A list of additional compiler arguments

Attributes common to JVM and JS

Restrict the use of declarations to those from the specified version of bundled libraries

«1.3» (DEPRECATED), «1.4» (DEPRECATED), «1.5», «1.6», «1.7» (EXPERIMENTAL)

Provide source compatibility with the specified version of Kotlin

«1.4» (DEPRECATED), «1.5», «1.6», «1.7» (EXPERIMENTAL)

Attributes specific to JVM

Generate metadata for Java 1.8 reflection on method parameters

Include a custom JDK from the specified location into the classpath instead of the default JAVA_HOME. Direct setting is deprecated sinСЃe 1.5.30, use other ways to set this option.

Target version of the generated JVM bytecode

«1.6» (DEPRECATED), «1.8», «9», «10», «11», «12», «13», «14», «15», «16», «17»

Don’t automatically include the Java runtime into the classpath

Attributes specific to JS

Disable internal declaration export

Define whether the main function should be called upon execution

Generate .meta.js and .kjsm files with metadata. Use to create a library

The kind of JS module generated by the compiler

«umd», «commonjs», «amd», «plain»

Don’t automatically include the default Kotlin/JS stdlib in compilation dependencies

Destination *.js file for the compilation result

Generate source map

Embed source files into the source map

«never», «always», «inlining»

Add the specified prefix to paths in the source map

Generate JS files for specific ECMA version

Translate primitive arrays to JS typed arrays

Generating documentation

To generate documentation for Kotlin projects, use Dokka; please refer to the Dokka README for configuration instructions. Dokka supports mixed-language projects and can generate output in multiple formats, including standard JavaDoc.

For OSGi support see the Kotlin OSGi page.

Using the Gradle Kotlin DSL

When using Gradle Kotlin DSL, apply Kotlin plugins using the plugins < . >block. If you apply them with apply < plugin(. ) >instead, you may encounter unresolved references to the extensions generated by Gradle Kotlin DSL. To resolve that, you can comment out the erroneous usages, run the Gradle task kotlinDslAccessorsSnapshot , then uncomment the usages back and rerun the build or reimport the project into the IDE.

Kotlin daemon and using it with Gradle

The Kotlin daemon:

Runs along with the Gradle daemon to compile the project.

Runs separately when you compile the project with an IntelliJ IDEA built-in build system.

The Kotlin daemon starts at the Gradle execution stage when one of Kotlin compile tasks starts compiling the sources. The Kotlin daemon stops along with the Gradle daemon or after two idle hours with no Kotlin compilation.

The Kotlin daemon uses the same JDK that the Gradle daemon does.

Setting Kotlin daemon’s JVM arguments

Each of the options in the following list overrides the ones that came before it:

If nothing is specified, the Kotlin daemon inherits arguments from the Gradle daemon. For example, in the gradle.properties file:

If the Gradle daemon’s JVM arguments have the kotlin.daemon.jvm.options system property – use it in the gradle.properties file:

You can add the kotlin.daemon.jvmargs property in the gradle.properties file:

You can specify arguments in the kotlin extension:

You can specify arguments for a specific task:

In this case a new Kotlin daemon instance can start on task execution. Learn more about Kotlin daemon’s behavior with JVM arguments.

Kotlin daemon’s behavior with JVM arguments

When configuring the Kotlin daemon’s JVM arguments, note that:

It is expected to have multiple instances of the Kotlin daemon running at the same time when different subprojects or tasks have different sets of JVM arguments.

A new Kotlin daemon instance starts only when Gradle runs a related compilation task and existing Kotlin daemons do not have the same set of JVM arguments. Imagine that your project has a lot of subprojects. Most of them require some heap memory for a Kotlin daemon, but one module requires a lot (though it is rarely compiled). In this case, you should provide a different set of JVM arguments for such a module, so a Kotlin daemon with a larger heap size would start only for developers who touch this specific module.

If you are already running a Kotlin daemon that has enough heap size to handle the compilation request, even if other requested JVM arguments are different, this daemon will be reused instead of starting a new one.

If the Xmx is not specified, the Kotlin daemon will inherit it from the Gradle daemon.

Источник

Оцените статью