Lesson 1: Scala Programming Language Tutorial
Lesson 1: Scala Programming Language Tutorial
Example 1: Hello, World! in Scala
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, World!")
}
}
Explanation:
object HelloWorld– Defines an object namedHelloWorld. In Scala,objectis used for defining a singleton instance.def main(args: Array[String]): Unit = {– This is the main method, the entry point of a Scala program.println("Hello, World!")– Prints "Hello, World!" to the console usingprintln.}– Closes themainmethod andHelloWorldobject.
Example 2: Variables and Data Types
val name: String = "Scala"
var age: Int = 5
age = 6
Explanation:
val name: String = "Scala"– Declares an immutable variablenameof typeString, storing "Scala".var age: Int = 5– Declares a mutable variableageof typeInt, initialized with5.age = 6– Modifiesagesince it is declared withvar, allowing reassignment.valvsvar–val nameis immutable, whilevar agecan be changed.
Example 3: Functions in Scala
def add(x: Int, y: Int): Int = {
x + y
}
println(add(3, 4))
Explanation:
def add(x: Int, y: Int): Int = {– Defines a functionaddthat takes twoIntparameters and returns anInt.x + y– Performs addition ofxandyand returns the result.}– Closes the function body.println(add(3, 4))– Callsadd(3, 4), printing7to the console.
Example 4: Looping with for
for (i <- 1 to 5) {
println(s"Iteration: $i")
}
Explanation:
for (i <- 1 to 5)– Aforloop that iterates from1to5inclusive.{ println(s"Iteration: $i") }– Inside the loop, prints the iteration number using string interpolation.s"Iteration: $i"– Usessbefore the string to insert variableidynamically.}– Closes the loop block.
This is Lesson 1 of Scala programming with basic examples and explanations.