Movatterモバイル変換


[0]ホーム

URL:


The Scala Plugin

version 8.14.3

The Scala plugin extends theJava plugin to add support forScala projects.The plugin also supportsjoint compilation, which allows you to freely mix and match Scala and Java code with dependencies in both directions.For example, a Scala class can extend a Java class that in turn extends a Scala class.This makes it possible to use the best language for the job, and to rewrite any class in the other language if needed.

Note that if you want to benefit from theAPI / implementation separation, you can also apply thejava-library plugin to your Scala project.

Usage

To use the Scala plugin, include the following in your build script:

build.gradle.kts
plugins {    id("scala")}
build.gradle
plugins {    id("scala")}

Tasks

The Scala plugin adds the following tasks to the project.Information about altering the dependencies to Java compile tasks are foundhere.

compileScalaScalaCompile

Depends on:compileJava

Compiles production Scala source files.

compileTestScalaScalaCompile

Depends on:compileTestJava

Compiles test Scala source files.

compileSourceSetScalaScalaCompile

Depends on:compileSourceSetJava

Compiles the given source set’s Scala source files.

scaladocScalaDoc

Generates API documentation for the production Scala source files.

TheScalaCompile andScalaDoc tasks supportJava toolchains out of the box.

The Scala plugin adds the following dependencies to tasks added by the Java plugin.

Table 1. Scala plugin - additional task dependencies
Task nameDepends on

classes

compileScala

testClasses

compileTestScala

sourceSetClasses

compileSourceSetScala

scalaPluginTasks
Figure 1. Scala plugin - tasks

Project layout

The Scala plugin assumes the project layout shown below. All the Scala source directories can contain Scalaand Java code. The Java source directories may only contain Java source code. None of these directories need to exist or have anything in them; the Scala plugin will simply compile whatever it finds.

src/main/java

Production Java source.

src/main/resources

Production resources, such as XML and properties files.

src/main/scala

Production Scala source. May also contain Java source files for joint compilation.

src/test/java

Test Java source.

src/test/resources

Test resources.

src/test/scala

Test Scala source. May also contain Java source files for joint compilation.

src/sourceSet/java

Java source for the source set namedsourceSet.

src/sourceSet/resources

Resources for the source set namedsourceSet.

src/sourceSet/scala

Scala source files for the given source set. May also contain Java source files for joint compilation.

Changing the project layout

Just like the Java plugin, the Scala plugin allows you to configure custom locations for Scala production and test source files.

build.gradle.kts
sourceSets {    main {        scala {            setSrcDirs(listOf("src/scala"))        }    }    test {        scala {            setSrcDirs(listOf("test/scala"))        }    }}
build.gradle
sourceSets {    main {        scala {            srcDirs = ['src/scala']        }    }    test {        scala {            srcDirs = ['test/scala']        }    }}

Scala version

The Scala version can be declared directly on thescala extension.Dependencies are automatically added to thescalaToolchain configuration based on the declared Scala version.ThescalaToolchainRuntimeClasspath configuration resolves the dependencies declared on thescalaToolchain configuration and contains files required to run the Scala compiler.

Direct dependencies on the Scala SDK do not need to be declared when thescalaVersion property is set.
build.gradle.kts
repositories {    mavenCentral()}scala {    scalaVersion = "2.13.12"}
build.gradle
repositories {    mavenCentral()}scala {    scalaVersion = "2.13.12"}

Configuring Gradle to use Scala 3 is no different from Scala 2.

build.gradle.kts
repositories {    mavenCentral()}scala {    scalaVersion = "3.6.3"}
build.gradle
repositories {    mavenCentral()}scala {    scalaVersion = "3.6.3"}
ThescalaVersion property is incubating.

Declaring Scala dependencies

When not using thescalaVersion property, the Scala SDK dependency must be declared manually on theimplementation configuration.This pattern is not preferred, as it relies oninferring the Scala classpath from the production runtime classpath.Omitting the Scala version from thescala extension will be deprecated in a future Gradle version.

Scala 2 projects need to declare ascala-library dependency.

build.gradle.kts
repositories {    mavenCentral()}dependencies {    implementation("org.scala-lang:scala-library:2.13.12")}
build.gradle
repositories {    mavenCentral()}dependencies {    implementation("org.scala-lang:scala-library:2.13.12")}

Scala 3 projects need to declare ascala3-library_3 dependency instead:

build.gradle.kts
repositories {    mavenCentral()}dependencies {    implementation("org.scala-lang:scala3-library_3:3.6.3")}
build.gradle
repositories {    mavenCentral()}dependencies {    implementation("org.scala-lang:scala3-library_3:3.6.3")}

If Scala is only used for test code, thescala-library dependency should be added to thetestImplementation configuration:

build.gradle.kts
dependencies {    testImplementation("org.scala-lang:scala-library:2.13.12")}
build.gradle
dependencies {    testImplementation("org.scala-lang:scala-library:2.13.12")}

Automatic configuration of scalaClasspath

TheScalaCompile andScalaDoc tasks consume Scala code in two ways: on theirclasspath, and on theirscalaClasspath.The former is used to locate classes referenced by the source code, and will typically containscala-library along with other libraries.The latter is used to load and execute the Scala compiler and Scaladoc tool, respectively, and should only contain thescala-compiler library and its dependencies.

If thescala extension’sscalaVersion property is not set and the task’sscalaClasspath is not configured explicitly, the Scala (base) plugin will try to infer the classpath from the task’sclasspath. This is done as follows:

  • If ascala-library jar is found onclasspath, and the project has at least one repository declared, a correspondingscala-compiler repository dependency will be added toscalaClasspath.

  • Otherwise, execution of the task will fail with a message saying thatscalaClasspath could not be inferred.

Configuring the Zinc compiler

The Scala plugin uses a configuration namedzinc to resolve theZinc compiler and its dependencies.Gradle will provide a default version of Zinc, but if you need to use a particular Zinc version, you can change it.Gradle supports version 1.6.0 of Zinc and above.

build.gradle.kts
scala {    scalaVersion = "2.13.12"    zincVersion = "1.10.4"}
build.gradle
scala {    scalaVersion = "2.13.12"    zincVersion = "1.10.4"}

The Zinc compiler itself needs a compatible version ofscala-library that may be different from the version required by your application.Gradle takes care of specifying a compatible version ofscala-library for you.

You can diagnose problems with the version of the Zinc compiler selected by runningdependencyInsight for thezinc configuration.

Table 2. Zinc compatibility table
Gradle versionSupported Zinc versionsZinc coordinatesRequired Scala versionSupported Scala compilation version

7.5 and newer

SBT Zinc. Versions 1.6.0 and above.

org.scala-sbt:zinc_2.13

Scala2.13.x is required forrunning Zinc.

Scala2.10.x through3.x can be compiled.

6.0 to 7.5

SBT Zinc. Versions 1.2.0 and above.

org.scala-sbt:zinc_2.12

Scala2.12.x is required forrunning Zinc.

Scala2.10.x through2.13.x can be compiled.

1.x through 5.x

Deprecated Typesafe Zinc compiler. Versions 0.3.0 and above, except for 0.3.2 through 0.3.5.2.

com.typesafe.zinc:zinc

Scala2.10.x is required forrunning Zinc.

Scala2.9.x through2.12.x can be compiled.

Adding plugins to the Scala compiler

The Scala plugin adds a configuration namedscalaCompilerPlugins which is used to declare and resolve optional compiler plugins.

build.gradle.kts
dependencies {    scalaCompilerPlugins("org.typelevel:kind-projector_2.13.12:0.13.2")}
build.gradle
dependencies {    scalaCompilerPlugins("org.typelevel:kind-projector_2.13.12:0.13.2")}

Convention properties

The Scala plugin does not add any convention properties to the project.

Source set properties

The Scala plugin adds the following extensions to each source set in the project. You can use these in your build script as though they were properties of the source set object.

scalaSourceDirectorySet (read-only)

The Scala source files of this source set. Contains all.scala and.java files found in the Scala source directories, and excludes all other types of files.Default value: non-null.

scala.srcDirsSet<File>

The source directories containing the Scala source files of this source set. May also contain Java source files for joint compilation.Can set using anything described inUnderstanding implicit conversion to file collections.Default value:[projectDir/src/name/scala].

allScalaFileTree (read-only)

All Scala source files of this source set. Contains only the.scala files found in the Scala source directories.Default value: non-null.

These extensions are backed by an object of typeScalaSourceSet.

The Scala plugin also modifies some source set properties:

Table 3. Scala plugin - source set properties
Property nameChange

allJava

Adds all.java files found in the Scala source directories.

allSource

Adds all source files found in the Scala source directories.

Target bytecode level and Java APIs version

When running the Scala compile task, Gradle will always add a parameter to configure the Java target for the Scala compiler that is derived from the Gradle configuration:

  • When using toolchains, the-release option, ortarget for older Scala versions, is selected, with a version matching the Java language level of the toolchain configured.

  • When not using toolchains, Gradle will always pass atarget flag — with exact value dependent on the Scala version — to compile to Java 8 bytecode.

This means that using toolchains with a recent Java version and an old Scala version can result in failures because Scala only supported Java 8 bytecode for some time.The solution is then to either use the right Java version in the toolchain or explicitly downgrade the target when needed.

The following table explains the values computed by Gradle:

Table 4. Scala target parameter based on project configuration
Scala versionToolchain in useParameter value

version <2.13.1

yes

-target:jvm-1.<java_version>

no

-target:jvm-1.8

2.13.1 <= version <2.13.9

yes

-target:<java_version>

no

-target:8

2.13.9 <= version <3.0

yes

-release:<java_version>

no

-target:8

3.0 <= version

yes

-release:<java_version>

no

-Xtarget:8

Setting any of these flags explicitly, or using flags containingjava-output-version, onScalaCompile.scalaCompileOptions.additionalParameters disables that logic in favor of the explicit flag.

Compiling in external process

Scala compilation takes place in an external process.

Memory settings for the external process default to the defaults of the JVM. To adjust memory settings, configure thescalaCompileOptions.forkOptions property as needed:

build.gradle.kts
tasks.withType<ScalaCompile>().configureEach {    scalaCompileOptions.forkOptions.apply {        memoryMaximumSize = "1g"        jvmArgs = listOf("-XX:MaxMetaspaceSize=512m")    }}
build.gradle
tasks.withType(ScalaCompile) {    scalaCompileOptions.forkOptions.with {        memoryMaximumSize = '1g'        jvmArgs = ['-XX:MaxMetaspaceSize=512m']    }}

Incremental compilation

By compiling only classes whose source code has changed since the previous compilation, and classes affected by these changes, incremental compilation can significantly reduce Scala compilation time. It is particularly effective when frequently compiling small code increments, as is often done at development time.

The Scala plugin defaults to incremental compilation by integrating withZinc, a standalone version ofsbt's incremental Scala compiler. If you want to disable the incremental compilation, setforce = true in your build file:

build.gradle.kts
tasks.withType<ScalaCompile>().configureEach {    scalaCompileOptions.apply {        isForce = true    }}
build.gradle
tasks.withType(ScalaCompile) {    scalaCompileOptions.with {        force = true    }}

Note: This will only cause all classes to be recompiled if at least one input source file has changed. If there are no changes to the source files, thecompileScala task will still be consideredUP-TO-DATE as usual.

The Zinc-based Scala Compiler supports joint compilation of Java and Scala code. By default, all Java and Scala code undersrc/main/scala will participate in joint compilation. Even Java code will be compiled incrementally.

Incremental compilation requires dependency analysis of the source code. The results of this analysis are stored in the file designated byscalaCompileOptions.incrementalOptions.analysisFile (which has a sensible default). In a multi-project build, analysis files are passed on to downstreamScalaCompile tasks to enable incremental compilation across project boundaries. ForScalaCompile tasks added by the Scala plugin, no configuration is necessary to make this work. For otherScalaCompile tasks that you might add, the propertyscalaCompileOptions.incrementalOptions.publishedCode needs to be configured to point to the classes folder or Jar archive by which the code is passed on to compile class paths of downstreamScalaCompile tasks. Note that ifpublishedCode is not set correctly, downstream tasks may not recompile code affected by upstream changes, leading to incorrect compilation results.

Note that Zinc’s Nailgun based daemon mode is not supported. Instead, we plan to enhance Gradle’s own compiler daemon to stay alive across Gradle invocations, reusing the same Scala compiler. This is expected to yield another significant speedup for Scala compilation.

Eclipse Integration

When the Eclipse plugin encounters a Scala project, it adds additional configuration to make the project work with Scala IDE out of the box. Specifically, the plugin adds a Scala nature and dependency container.

IntelliJ IDEA Integration

When the IDEA plugin encounters a Scala project, it adds additional configuration to make the project work with IDEA out of the box. Specifically, the plugin adds a Scala SDK (IntelliJ IDEA 14+) and a Scala compiler library that matches the Scala version on the project’s class path. The Scala plugin is backwards compatible with earlier versions of IntelliJ IDEA and it is possible to add a Scala facet instead of the default Scala SDK by configuringtargetVersion onIdeaModel.

build.gradle.kts
idea {    targetVersion = "13"}
build.gradle
idea {    targetVersion = '13'}
You can submit issues directly on Github.
© 2025 Gradle, Inc. Gradle®, Develocity®, Build Scan®, and the Gradlephant logo are registered trademarks of Gradle, Inc.
Gradle
Privacy |Terms of Service

[8]ページ先頭

©2009-2025 Movatter.jp