Lesson 4: Scala Programming Language Tutorial
Lesson 4: Scala Programming Language Tutorial
This lesson provides four Scala code examples, each explained in four detailed points of around 25 words each. Each explanation point repeats the relevant code fragment for clarity.
Example 1: Traits in Scala
trait Animal {
def makeSound(): String
}
class Dog extends Animal {
def makeSound(): String = "Bark"
}
val myDog = new Dog()
println(myDog.makeSound())
Explanation:
trait Animal { def makeSound(): String }
– Defines atrait
namedAnimal
, which acts as an interface requiring the methodmakeSound
to be implemented by subclasses.class Dog extends Animal { def makeSound(): String = "Bark" }
– TheDog
class extendsAnimal
, implementingmakeSound
to return"Bark"
, fulfilling the trait’s contract.val myDog = new Dog()
– Instantiates an objectmyDog
from theDog
class, which automatically inherits themakeSound
method from theAnimal
trait.println(myDog.makeSound())
– CallsmakeSound()
onmyDog
, printing"Bark"
. This demonstrates how traits enforce method definitions and allow reuse across multiple classes.
Example 2: Companion Objects in Scala
class Person(val name: String)
object Person {
def create(name: String): Person = new Person(name)
}
val john = Person.create("John")
println(john.name)
Explanation:
class Person(val name: String)
– Defines a classPerson
with a primary constructor that initializes the immutablename
property when a new object is created.object Person { def create(name: String): Person = new Person(name) }
– Declares a companion objectPerson
, containing a factory methodcreate
that constructs aPerson
instance.val john = Person.create("John")
– Calls thecreate
method fromPerson
’s companion object, instantiating aPerson
object with"John"
as thename
.println(
john.name
)
– Printsjohn.name
, outputting"John"
. This pattern is useful for factory methods and ensuring controlled object creation.
Example 3: Case Classes and Pattern Matching
case class User(name: String, age: Int)
val user = User("Alice", 25)
user match {
case User("Alice", 25) => println("Matched Alice!")
case _ => println("No match found.")
}
Explanation:
case class User(name: String, age: Int)
– Defines acase class
namedUser
. Case classes automatically generate equality checks,toString
, andcopy
methods, simplifying data modeling.val user = User("Alice", 25)
– Instantiates aUser
object without usingnew
. Case classes provide concise object creation syntax, improving readability.user match { case User("Alice", 25) => println("Matched Alice!")
– Uses pattern matching to check ifuser
hasname = "Alice"
andage = 25
. If true,"Matched Alice!"
is printed.case _ => println("No match found.")
– The wildcard_
case ensures all unmatched values print"No match found."
, demonstrating exhaustive pattern matching in Scala.
Example 4: Futures and Asynchronous Programming
import scala.concurrent.{Future, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global
val futureResult = Future {
Thread.sleep(1000)
"Task Completed"
}
futureResult.foreach(println)
Thread.sleep(2000)
Explanation:
import scala.concurrent.{Future, ExecutionContext}
– Imports necessary classes to useFuture
, a feature that allows concurrent computation execution without blocking the main thread.val futureResult = Future { Thread.sleep(1000); "Task Completed" }
– Creates aFuture
that simulates an asynchronous task by sleeping for1
second before returning"Task Completed"
.futureResult.foreach(println)
– Attaches a callback usingforeach
, printing"Task Completed"
when the future finishes execution asynchronously.Thread.sleep(2000)
– Ensures the main thread waits2
seconds to let the future complete, demonstrating non-blocking asynchronous programming in Scala.