Define a Scala or Java Library Target

Problem

You need to define a new Scala or Java library target that other projects can use as a dependency.

Note: If you need to define a new Scala or Java binary target, see Define a JVM Executable

Solution

Add a scala_library or java_library target to a BUILD file in the appropriate directory. A scala_library or java_library target will enable you to compile the library using Pants' compile goal. Here's an example:

$ ./pants compile src/scala/com/myorg/myproject/example:hello

Discussion

A scala_library or java_library target should specify the following:

  • A name for the library. This may be something like just scala if you have only one scala_library target in a project or something more specific like client-lib.
  • Either the source field with a single file or the sources field with a list of file names and globs.
  • A list of dependencies (optional). More info on dependencies can be found in Add a Dependency on Another Target.

Here's an example target definition:

# src/scala/com/myorg/myproject/example/BUILD
scala_library(
  name='scala',
  sources=['*.scala'],
  dependencies=[
    'src/scala/com/myorg/myproject/client-lib',
    'src/scala/com/myorg/myproject/analytics-lib',
    'static/resources/json:config',
  ],
)

That library can then be compiled with:

$ ./pants compile src/scala/com/myorg/myproject/example

You can combine library targets together into a single target using a target aggregate. More info can be found in Create a Target Aggregate.

See Also

Generated by publish_docs from dist/markdown/html/src/docs/common_tasks/jvm_library.html 2022-12-03T01:08:59.566347