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

Настройка и основы проектов SBT

Научитесь создавать новые проекты SBT, определять настройки и выполнять распространённые задачи сборки.

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

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

Welcome to SBT!

Hello! Today we're diving into SBT, the standard build tool for Scala projects. Think of it as your project's manager, handling everything from compiling code to running tests and packaging your application.

SBT stands for Scala Build Tool. It simplifies complex tasks and ensures your projects are set up correctly.

Why Use SBT?

SBT brings several benefits to Scala development:

  • Dependency Management: Easily add external libraries your project needs.
  • Project Structure: Enforces a standard layout, making projects easy to navigate.
  • Task Automation: Automate compilation, testing, packaging, and more with simple commands.
  • Consistency: Ensures everyone on a team builds and runs the project in the same way.

Getting SBT Installed

Before we can use SBT, we need to install it. The recommended way is often through a package manager like Coursier or Homebrew (on macOS/Linux) or by downloading the official launcher.

Once installed, you can verify it by checking the version in your terminal:

sbt --version

Creating a New Project

SBT provides a convenient way to create new projects using templates. We'll use the sbt new command with a basic Scala seed template.

This command will set up the necessary directories and files for a simple Scala application:

sbt new scala/scala-seed.g8 --name my-first-sbt-app

Exploring Project Structure

After creating my-first-sbt-app, you'll see a standard directory structure:

  • src/main/scala/: Your main Scala source code goes here.
  • src/test/scala/: For your test files.
  • project/: Contains project-specific SBT configurations.
  • build.sbt: The main configuration file for your project.

The build.sbt file is where you define project settings.

Basic build.sbt Configuration

The build.sbt file uses a simple syntax to define project settings. Here's a basic example:

  • name := "my-first-sbt-app": Sets your project's name.
  • version := "0.1.0-SNAPSHOT": Defines the project's version.
  • scalaVersion := "2.13.12": Specifies the Scala version to use.

These are key-value pairs where := assigns a value to a setting.

name := "my-first-sbt-app"
version := "0.1.0-SNAPSHOT"
scalaVersion := "2.13.12"

Your First Scala Program

Let's add a simple Scala program to our project. Inside src/main/scala/, create a file named Main.scala. This program will just print a greeting.

SBT will automatically find and compile this file when you run commands like compile or run.

object Main {
  def main(args: Array[String]): Unit = {
    println("Hello from SBT!")
  }
}

Running Your Application

With your Main.scala file in place, navigate to your project's root directory in the terminal (e.g., cd my-first-sbt-app).

You can then use the sbt run command. SBT will compile your code and execute the main method it finds.

sbt run

The SBT Interactive Shell

You can also enter the SBT interactive shell by just typing sbt in your project's root directory. This keeps SBT running, making subsequent commands faster.

Inside the shell, you can type commands like compile, run, or test directly. Type exit to leave the shell.

sbt

> compile
> run
> exit

Quick Check: SBT Basics

Which of the following settings is typically used in build.sbt to specify the Scala version for your project?

SBT Journey Continues!

Great job! You've taken your first steps with SBT.

We covered:

  • What SBT is and why it's essential.
  • How to set up a new SBT project.
  • Understanding the basic project structure.
  • Configuring fundamental settings in build.sbt.
  • Running your first Scala application using SBT commands.

Next, we'll explore how to manage external libraries and use SBT plugins to extend your project's capabilities!

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

Урок «Настройка и основы проектов SBT» бесплатный?

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

Чему я научусь в уроке «Настройка и основы проектов SBT»?

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

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

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

Сколько времени занимает урок «Настройка и основы проектов SBT»?

Большинство уроков 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