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 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
Scala | Methods to Call Option The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. There are a few methods that
5 min read
How to Install Scala IDE For Eclipse? In this tutorial, we'll look at how to set up the Eclipse IDE for Scala. This tutorial is for those who are new to Scala. Requirement for InstallationEclipse (Install link) if you don't know how to install Eclipse then refer to this article.JDK 11 (you may use JDK 6 onwards) Note: If you do not have
2 min read
How to Read and Write CSV File in Scala? Data processing and analysis in Scala mostly require dealing with CSV (Comma Separated Values) files. CSV is a simple file format used to store tabular data, such as a spreadsheet or database. Each line of a CSV file is plain text, representing a data row, with values separated by commas (,). Readin
5 min read
How to check Scala version in mac? Scala is a powerful and versatile programming language that combines features of two popular programming paradigms: Object-oriented and Functional. These are the features of the Scala programming language: Multi-paradigmObject-OrientedFunctional ProgrammingJVM and BeyondStatically TypedTo check the
1 min read
How to import dbutils in Scala? In Scala, dbutils typically refers to a utility library provided by Databricks for interacting with databases and performing data-related tasks within Databricks environments. To import dbutils in Scala, follow these steps: Steps:Open a Databricks Notebook: First, ensure you're working within a Data
2 min read
How to define Optional Parameter in Scala? Optional parameters in Scala provide us with a procedure or a way to define some default values for function parameters. The need to define default values comes when a value is not provided for the parameter during function invocation. These are also useful when we want to provide some default or sp
5 min read