How to add Dependency in Scala?
Last Updated :
21 Jun, 2024
Scala, a strong language that unites both object-oriented and functional programming techniques has to depend on external libraries to enhance its capabilities. To develop projects seamlessly, there must be efficient handling of these libraries. This is where dependency management becomes important. In this article, we will see the process of adding Scala dependencies with examples and step-by-step procedures.
Setting Up the Environment
To work with Scala, you need to set up your development environment. Ensure you have Scala installed and a build tool like SBT (Scala Build Tool).
1. Create a New Project Using SBT
sbt new scala/scala-seed.g8
Inside your project directory, there is a build.sbt file. This file will contain your project's configuration, including dependencies.
Creating a Scala Project2. Define Your Project in build.sbt
Open build.sbt and define your project settings.
Example:
name := "MyScalaProject",
version := "0.1",
scalaVersion := "2.13.6",
3. Add Dependencies
Dependencies are added under the libraryDependencies setting.
For example, to add the popular JSON library play-json, your build.sbt might look like this:
lazy val root = (project in file("."))
.settings(
name := "MyScalaProject",
version := "0.1",
scalaVersion := "2.13.6",
libraryDependencies += munit % Test,
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.2"
)
Adding Dependencies4. Fetch and Use Dependencies
Once you have defined your dependencies, you need to fetch them.
Run the following command in your project directory:
sbt update
Updating Project5. Run Your Project
Run the following command in your project directory:
sbt run
Running Scala ProjectExample 1: Adding Akka HTTP
1. Adding Akka HTTP Dependencies
libraryDependencies += "com.typesafe.akka" %% "akka-http" % "10.2.7",
libraryDependencies += "com.typesafe.akka" %% "akka-actor-typed" % "2.6.19",
libraryDependencies += "com.typesafe.akka" %% "akka-stream" % "2.6.19"
2. Complete build.sbt
import Dependencies._
ThisBuild / scalaVersion := "2.13.12"
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / organization := "com.example"
ThisBuild / organizationName := "example"
lazy val root = (project in file("."))
.settings(
name := "MyScalaProject",
version := "0.1",
scalaVersion := "2.13.9",
libraryDependencies += munit % Test,
libraryDependencies += "com.typesafe.akka" %% "akka-http" % "10.2.7",
libraryDependencies += "com.typesafe.akka" %% "akka-actor-typed" % "2.6.19",
libraryDependencies += "com.typesafe.akka" %% "akka-stream" % "2.6.19"
)
3. Implementation Code
Scala
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
object Example1 extends App {
implicit val system = ActorSystem("my-system")
implicit val executionContext = system.dispatcher
val route = path("hello") {
get {
complete("Hello, Akka HTTP!")
}
}
Http().newServerAt("localhost", 8080).bind(route)
}
Output:
Running Scala Akka HTTPExample #2 Adding ScalaTest
1. Adding ScalaTest Dependencies
libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.16" % Test
2. Complete build.sbt
import Dependencies._
ThisBuild / scalaVersion := "2.13.12"
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / organization := "com.example"
ThisBuild / organizationName := "example"
lazy val root = (project in file("."))
.settings(
name := "MyScalaProject",
version := "0.1",
scalaVersion := "2.13.9",
libraryDependencies += munit % Test,
libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.16" % Test
)
3. Test Implementation Code
Scala
package example
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class Test2 extends AnyFlatSpec with Matchers {
"A String" should "have the correct length" in {
"Scala".length shouldEqual 5
}
}
Output:
Running Scala TestExample #3 Adding scala-csv Library
1. Adding scala-csv Dependencies
libraryDependencies += "com.github.tototoshi" %% "scala-csv" % "1.3.10"
2. Complete build.sbt
import Dependencies._
ThisBuild / scalaVersion := "2.13.12"
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / organization := "com.example"
ThisBuild / organizationName := "example"
lazy val root = (project in file("."))
.settings(
name := "CsvWork",
libraryDependencies += munit % Test,
libraryDependencies += "com.github.tototoshi" %% "scala-csv" % "1.3.10"
)
3. Implementation Code
Scala
import scala.io.Source
object Example3 {
def main(args: Array[String]): Unit = {
val filename = "data.csv"
val delimiter = ","
val file = Source.fromFile(filename)
for (line <- file.getLines()) {
val fields = line.split(delimiter).map(_.trim)
println(fields.mkString(", "))
}
file.close()
}
}
Output:
Running Scala CSVConclusion
It is easy to add dependencies in Scala particularly if you are working with sbt. By defining dependencies in the build.sbt file, you can easily manage and use external libraries, enhancing your project's capabilities and efficiency. You should be confident with adding and utilizing these kinds of stuffs into your scala jobs using the examples provided.
Similar Reads
How to do Exponentiation in Scala?
This article focuses on discussing implementing exponentiation in Scala. The math.pow() function from the scala.math package is used for exponentiation in Scala. Table of Content Basic ApproachUsing BigDecimalWith Long Data TypesSyntax: val result = pow(base, exponent) Basic ApproachBelow is the Sca
1 min read
How To Manage Dependencies in Git?
Managing dependencies is very important for software development, ensuring that your project runs smoothly and is maintainable over time. In Git, managing these dependencies effectively can prevent conflicts, reduce errors, and simplify collaboration within your team. In this article, we'll explore
6 min read
How to add new line Scala?
In this article, we will learn how to add a new line in Scala. 1. Using the newline character (\n):This is the most straightforward approach. The \n character represents a newline and will be interpreted as such when the string is printed. Scala // Creating object object GfG { // Main method def mai
2 min read
How to Execute OS Commands in Scala?
Scala is a versatile programming language. It offers smooth approaches to running OS instructions, whether or not you want to deal with documents, automate system operations, or communicate with external gear. This article focuses on discussing ways to execute OS commands in Scala. PrerequisitesInst
2 min read
How to Check Datatype in Scala?
In this article, we will learn to check data types in Scala. Data types in Scala represent the type of values that variables can hold, aiding in type safety and program correctness. Table of Content Checking Datatype in ScalaApproach 1: Use Pattern Matching in ScalaApproach 2: Use the getClass Metho
3 min read
Scala Path Dependent Type
Scala Path Dependent Types (PDTs) are an advanced feature of the Scala language that allows users to create types that are dependent on the path in which they are accessed. The type of a variable or object is not determined by its own structure or characteristics, but rather by the path in which it
4 min read
How to check if a file exists in Scala?
When working on software projects it's crucial to check if a file exists before you interact with it in any way such as reading, writing, or modifying it. This practice helps avoid issues that may arise from attempting to handle an existing file. Scala provides methods to perform this check for the
2 min read
How to Add Element in an Immutable Seq in Scala?
In this article, we will learn how to add elements in immutable seq in Scala. immutable sequences, such as List, cannot have elements added to them directly because they are designed to be immutable. However, you can create a new sequence with an additional element by using methods like :+ (for appe
2 min read
How to Reduce Code Duplication in Scala?
For this definition, duplicate code refers to a sequence of source code that appears more than once in a program, whether inside the same program or across various programs owned or maintained by the same company. For a variety of reasons, duplicate code is typically seen as bad. A minimal requireme
8 min read
How to Sort a list in Scala?
Sorting a list is a common operation in programming, and Scala provides convenient ways to accomplish this task. In this article, we'll explore different methods to sort a list in Scala, along with examples. Table of Content Using the sorted Method:Using the sortBy Method:Using the sortWith Method:S
2 min read