Selected Reading

Scala - Keywords



Keywords are reserved words in Scala. Keywords are special reserved words which have predefined meanings and actions. No one can use these words as Identifiers, otherwise there will be compilation errors.

The following list shows the reserved words in Scala. These reserved words may not be used as constant or variable or any other identifier names.

Keywords Description
abstract Used to define abstract classes or traits.
case Used in pattern matching and for case classes.
catch Part of try-catch exception handling.
class Used to define a class.
def Used to define a method or function.
do Used in a do-while loop.
else Used in conditional expressions.
extends Used to indicate inheritance.
false A Boolean literal representing "false."
final Indicates that a class or method cannot be overridden or extended.
finally Part of try-catch-finally exception handling.
for Used to create loops and comprehensions.
if Used in conditional expressions.
import Used to import classes, objects, and methods from other packages.
match Used for pattern matching.
new Used to create new instances of classes.
null Represents a null value.
object Used to define a singleton object.
package Used to declare a package.
private Indicates that a member (class, method, etc.) is private.
protected Indicates that a member is protected.
return Used to return a value from a method.
sealed Used to restrict inheritance to a limited set of classes.
super Used to refer to a superclass.
this Used to refer to the current instance.
throw Used to throw an exception.
trait Used to define a trait.
true A Boolean literal representing "true."
try Used to start an exception handling block.
type Used to define type aliases.
val Used to declare an immutable (read-only) variable.
var Used to declare a mutable variable.
while Used in while loops.
with Used for mixin composition.
yield Used in for comprehensions to yield values.

Example of Scala Keywords

This example program contains various above keywords to learn −

// Keywords Examples

// import
import java.util.{Date, Calendar}

// abstract, class
abstract class Shape {
   def area(): Double
}

// case, match
case class Circle(radius: Double) extends Shape {
   def area(): Double = math.Pi * radius * radius
}

// object
object Greeting {
   def sayHello() = println("Hello, World!")
}

// final
final class MyImmutableClass {
   // This class cannot be extended
}

// super
class Parent {
   def display() = println("Parent class")
}

class Child extends Parent {
   def displayChild() = {
      super.display()
      println("Child class")
   }
}

class Animal {}
// extends
class Dog extends Animal

object Main {
   def main(args: Array[String]): Unit = {
      // catch, try
      try {
         val result = 10 / 0
      } catch {
         case e: ArithmeticException => println("ArithmeticException caught")
      }

      // def
      def square(x: Int): Int = x * x

      // if, else
      val num = 42
      if(num % 2 == 0) {
         println("Even")
      } else {
         println("Odd")
      }

      // match
      val day = 2
      val dayName = day match {
         case 1 => "Monday"
         case 2 => "Tuesday"
         case _ => "Other"
      }

      // val
      val pi = 3.14159265

      // var
      var counter = 0
      counter += 1

      // while
      var i = 0
      while (i < 5) {
         println(i)
         i += 1
      }

      // yield
      val numbers = List(1, 2, 3, 4, 5)
      val squares = for (n <- numbers) yield n * n
      
      // true, false
      val isSunny = true
      val isRainy = false

  }
}

Scala Reserved Special Operators

Scala also has following reserved special operators −

Special Operators Description
=> (Right Arrow) Used to define function or method parameters and return types in function literals.
<- (Left Arrow) Used in for-comprehensions for pattern matching and value assignment.
<: Used in type bounds and variance annotations.
:> Used in type bounds.
_ (Underscore) Used as a wildcard in pattern matching and function literals.
... (Ellipsis) Used to represent a variable number of arguments in function parameters.
< (Less Than) Used in type parameter constraints.
> (Greater Than) Used in type parameter constraints.
# (Pound) Used in context bounds.
@ (At) Used in annotations.

Example of Scala Reserved Special Operators

This example program contains various above special operators to learn −

object Main {
   def main(args: Array[String]): Unit = {
      // Right Arrow (=>) for function definitions
      val add: (Int, Int) => Int = (x, y) => x + y

      // Left Arrow (<-) for pattern matching
      val list = List(1, 2, 3)
      for {
         number <- list
      } println(s"Number: $number")

      // Less Than (<) and Greater Than (>) for comparisons
      val lessThan = 5 < 10
      val greaterThan = 10 > 5

      // Pound (#) for type bounds
      def foo[A <: Number](x: A) = println(s"Received: $x")

      // At (@) for annotations
      @deprecated("This method is deprecated", "1.0")
      def deprecatedMethod() = println("This is a deprecated method")

      // Underscore (_) for wildcards and placeholders
      val numbers = List(1, 2, 3, 4, 5)
      val squares = numbers.map(_ * 2)

      // Ellipsis (...) for varargs in method definition
      def printArgs(args: Any*) = args.foreach(println)

      // Colon and Right Angle (:>) for type annotations
      val x: Int = 42

      // Using symbols within identifiers
      val x_2: Int = 10
      val foo_bar = "Hello, World!"
  }
}
Advertisements