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 atraitnamedAnimal, which acts as an interface requiring the methodmakeSoundto be implemented by subclasses.class Dog extends Animal { def makeSound(): String = "Bark" }– TheDogclass extendsAnimal, implementingmakeSoundto return"Bark", fulfilling the trait’s contract.val myDog = new Dog()– Instantiates an objectmyDogfrom theDogclass, which automatically inherits themakeSoundmethod from theAnimaltrait.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 classPersonwith a primary constructor that initializes the immutablenameproperty when a new object is created.object Person { def create(name: String): Person = new Person(name) }– Declares a companion objectPerson, containing a factory methodcreatethat constructs aPersoninstance.val john = Person.create("John")– Calls thecreatemethod fromPerson’s companion object, instantiating aPersonobject 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 classnamedUser. Case classes automatically generate equality checks,toString, andcopymethods, simplifying data modeling.val user = User("Alice", 25)– Instantiates aUserobject 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 ifuserhasname = "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 aFuturethat simulates an asynchronous task by sleeping for1second 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 waits2seconds to let the future complete, demonstrating non-blocking asynchronous programming in Scala.