Scala Tutorial
Introduction to Scala
Scala is a modern programming language that blends object-oriented and functional programming styles. It is designed to be concise, elegant, and type-safe. Scala runs on the Java Virtual Machine (JVM) and is compatible with existing Java code.
Setting Up Scala
To set up Scala on your machine, follow these steps:
- Download and install the Java Development Kit (JDK).
- Download and install Scala from the official Scala website.
- Install an Integrated Development Environment (IDE) like IntelliJ IDEA, which supports Scala development.
Basic Syntax
Scala syntax is similar to Java, but it includes many enhancements. Here's a simple "Hello, World!" example:
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, World!")
}
}
In this example:
object HelloWorld
defines a singleton object namedHelloWorld
.def main(args: Array[String]): Unit
defines the main method, which is the entry point of the application.println("Hello, World!")
prints the string "Hello, World!" to the console.
Variables and Data Types
Scala has two types of variables: mutable and immutable.
var
defines a mutable variable.val
defines an immutable variable.
Here is an example of how to declare variables in Scala:
var mutableVariable: Int = 10
val immutableVariable: String = "Scala"
Control Structures
Scala supports various control structures, including conditional statements and loops.
If-Else Statement
val x = 10
if (x > 0) {
println("x is positive")
} else {
println("x is non-positive")
}
For Loop
for (i <- 1 to 5) {
println(i)
}
While Loop
var i = 0
while (i < 5) {
println(i)
i += 1
}
Functions
Functions in Scala are first-class citizens. Here's how you can define and use functions:
def add(a: Int, b: Int): Int = {
a + b
}
println(add(2, 3)) // Output: 5
Classes and Objects
Scala is an object-oriented language and supports classes and objects.
Class Definition
class Person(val name: String, val age: Int) {
def greet(): Unit = {
println(s"Hello, my name is $name and I am $age years old.")
}
}
val person = new Person("Alice", 30)
person.greet()
Functional Programming
Scala supports functional programming features such as higher-order functions and immutable data structures.
Higher-Order Functions
def applyFunction(f: Int => Int, x: Int): Int = {
f(x)
}
val increment: Int => Int = (x: Int) => x + 1
println(applyFunction(increment, 5)) // Output: 6
Collections
Scala provides a rich set of collection libraries. Here are some commonly used collections:
List
val list = List(1, 2, 3, 4, 5)
list.foreach(println)
Map
val map = Map("a" -> 1, "b" -> 2, "c" -> 3)
map.foreach { case (key, value) => println(s"$key -> $value") }
Pattern Matching
Pattern matching is a powerful feature in Scala that allows you to match on the structure of data:
val number = 6
number match {
case 1 => println("One")
case 2 => println("Two")
case _ => println("Other number")
}
Concurrency
Scala provides various tools for concurrent and parallel programming, including the Future
and Promise
APIs.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val future = Future {
Thread.sleep(1000)
42
}
future.onComplete {
case Success(value) => println(s"Got the result: $value")
case Failure(e) => println(s"Failed with exception: $e")
}
Conclusion
Scala is a versatile language that supports both object-oriented and functional programming paradigms. By learning Scala, you can leverage its powerful features to build robust and scalable applications.