0Pricing
Scala for Backend Engineering & Functional Programming · Урок

Управление зависимостями и плагины

Управляйте внешними библиотеками, объявляйте зависимости и используйте плагины SBT для расширения возможностей сборки.

«Управление зависимостями и плагины» — бесплатный урок Scala for Backend Engineering & Functional Programming на CoddyKit. Это урок 2 из 3. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Scala for Backend Engineering & Functional Programming, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Scala for Backend Engineering & Functional Programming содержит 3 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why External Libraries?

When building Scala projects, you often need functionality that isn't part of the core language. Things like logging, database access, or web frameworks are common examples.

Instead of writing all this code yourself, you can use external libraries (also called dependencies). These are pre-written code packages that other developers have created and shared.

Adding Libraries to build.sbt

SBT makes it easy to add these external libraries. You declare them in your build.sbt file using the libraryDependencies setting.

Here's the basic syntax:

  • "org.group": The organization or group ID.
  • % "artifact": The artifact ID (library name). Use %% for Scala libraries to automatically match your Scala version.
  • % "version": The specific version of the library you want.

Example:

libraryDependencies += "org.slf4j" % "slf4j-simple" % "1.7.32"

Dependency Scopes: Compile & Test

Libraries might only be needed for specific parts of your project. SBT uses scopes to manage this.

  • compile (default): Needed for compiling and running your main code.
  • test: Only needed for compiling and running your test code (e.g., a testing framework like ScalaTest).
  • runtime: Not needed for compilation, but required when the application runs.

You specify the scope like this:

libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.16" % "test"

Automatic Dependency Fetching

Imagine a library you use, like a web framework, also uses other libraries itself. These are called transitive dependencies.

SBT automatically handles fetching all these indirect dependencies for you. When you add a library, SBT looks up its own dependencies and downloads them too, ensuring your project has everything it needs.

This saves you from manually tracking dozens of libraries!

Logging with SLF4J

Let's use a common logging library, SLF4J (Simple Logging Facade for Java), with its simple implementation. First, add it to your build.sbt:

libraryDependencies += "org.slf4j" % "slf4j-simple" % "1.7.32"

Now, run the Scala code below to see it in action. Notice how we import org.slf4j.LoggerFactory, which comes from our new dependency.

import org.slf4j.LoggerFactory

object Main {
  private val logger = LoggerFactory.getLogger(getClass.getName)

  def main(args: Array[String]): Unit = {
    logger.info("Hello from a logged message!")
    println("This is a standard print output.")
  }
}

Extending SBT with Plugins

Beyond managing libraries, SBT itself can be extended using plugins. Plugins are special JAR files that add new commands or settings to SBT.

For example, there are plugins for packaging applications, deploying to servers, or even for integrating with specific tools like code formatters.

They help automate common tasks and streamline your development workflow.

Declaring Plugins in plugins.sbt

Unlike regular dependencies that go into build.sbt, SBT plugins are declared in a special file: project/plugins.sbt. This file lives inside the project directory at the root of your SBT project.

The syntax is similar to dependencies, but you use addSbtPlugin:

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.1.1")

This tells SBT to download and enable the specified plugin for your project.

Creating a Fat JAR with sbt-assembly

One popular plugin is sbt-assembly. It creates a single, executable "fat JAR" containing your application's code and all its dependencies.

First, add the plugin to project/plugins.sbt:

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.1.1")

After adding it, you can run sbt assembly from your terminal to create the JAR. The Scala code below is what sbt-assembly would package.

object Main {
  def main(args: Array[String]): Unit = {
    println("This is a simple application.")
    println("sbt-assembly would package this along with its dependencies into a single JAR.")
  }
}

Version Management & Resolvers

As your project grows, managing many dependencies can be tricky. Here are some tips:

  • Consistent Versions: Use the same version for a library across all modules to avoid conflicts.
  • Resolvers: SBT fetches libraries from repositories (like Maven Central). You can add custom resolvers if a library isn't in the default ones.

By default, SBT uses standard public repositories. For private libraries, you'd specify a custom resolver in build.sbt.

Order the Steps

You want to add a new external library to your Scala project and use it. Put the following steps in the correct order.

Lesson Summary

Great job! You've learned how to manage external code in your Scala projects.

  • Dependencies (libraries) are added to build.sbt using libraryDependencies.
  • SBT handles transitive dependencies and supports different scopes (like compile and test).
  • Plugins extend SBT's functionality and are declared in project/plugins.sbt using addSbtPlugin.

Mastering dependency and plugin management is key to building complex and robust Scala applications efficiently!

Часто задаваемые вопросы

Урок «Управление зависимостями и плагины» бесплатный?

Да — полный текст урока «Управление зависимостями и плагины» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Scala for Backend Engineering & Functional Programming, подпишись на CoddyKit PRO. Курс Scala for Backend Engineering & Functional Programming содержит 3 уроков всего.

Чему я научусь в уроке «Управление зависимостями и плагины»?

Управляйте внешними библиотеками, объявляйте зависимости и используйте плагины SBT для расширения возможностей сборки. Ты практикуешь Scala for Backend Engineering & Functional Programming с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Scala for Backend Engineering & Functional Programming?

Предыдущий опыт не требуется. Scala for Backend Engineering & Functional Programming на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 3.

Сколько времени занимает урок «Управление зависимостями и плагины»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Scala for Backend Engineering & Functional Programming?

Да. Каждый урок Scala for Backend Engineering & Functional Programming включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Настройка и основы проектов SBT
  2. Управление зависимостями и плагины
  3. Сборка и развёртывание нескольких проектов
← Назад к Scala for Backend Engineering & Functional Programming