Tutorials Hut




  • Scala Classes and Objects

    Class is a blueprint of any real life object, for example Tree can be a class representing real world tree objects. Instance of the class is called an object for example if we create a tree1 instance from the Tree class then it will be called an object of the Tree class.

     Classes and objects in Scala are similar to Java.

    class object methods

    Example of Class and Object

    In the below example Tree is a class and TreeDemo is showing how to create an object of it tree1 and use the class methods and members.
    class Tree(noOfBranches: Int, treeLocation: String) { //Class with constructor
      val treeAge = 50
      def printTreeDetails(): Unit = {
    	println("Tree branches: "+noOfBranches+" Tree Location: "+treeLocation)
      }
    }
     
    object TreeDemo{
      def main(args: Array[String]): Unit = {
    	val tree1 = new Tree(10, "USA") //Object
    	tree1.printTreeDetails()
    	println(tree1.treeAge)
      }
    }

    Constructors in Scala Class

     A constructor is used to create instances of a class and initialize the class variables. If a class has no specific constructor then a default constructor without any arguments is assigned by Scala internally and no explicit declaration needed.

    Example:

    In the below example, we can see the Tree class has a constructor which takes two arguments: first noOfBranches (Int type)and treeLocation (String type).

    class Tree(noOfBranches: Int, treeLocation: String) { //Class with constructor
     val treeAge = 50
     def printTreeDetails(): Unit = { //method in scala
    println("Tree branches: "+noOfBranches+" Tree Location: "+treeLocation)
     }
    }

    Object or Singleton Object in Scala

    In Scala we can declare an object directly which is similar to class but with the key word “object”, it is singleton by default. We can access all members of the object with the name of the object and no need to create an instance.

    Example:

    In the below example SingletonExample and Demo both are singleton objects and we can see how we can use SingletonExample objects.

    object SingletonExample {
    def display() = {
    println("Hello")
     }
    }

    object Demo {
    def main(args: Array[String]): Unit = {
    SingletonExample.display()
    }
    }

    Output:

    Hello

    Companion Object and Companion Class in Scala

    If we declare an Object/Singleton class with the same name of a class then it is called a Companion object and the class is called companion class. Companion class can access private members of the companion object as well.

    Example:

    Check below example where MyClass is a companion class and with the same name a companion object is created as well.

    class MyClass { //Companion class
       def printFilename() = {
       println(SomeClass.HiddenFilename) // private member is accessed
       }
    }

    object MyClass { //Companion object
       private val HiddenFilename = "/test/team.txt"
    }

    Inheritance/Extend In Scala

    Similar to java a child class can extend or inherit the property of a parent class and use them, we use extend keyword to do so.

    Example:

    Below ExtendExample is parent class and ExtendChildClass is child class.

    class ExtendExample {
    def dummyM1(): Unit = {
    println("I am dummy m1")
    }
    }</code>
    
    class ExtendChildClass extends ExtendExample {
    def dummyM2(): Unit = {
    println("I am dummy m2, going to call extended class method dummyM1()")
    dummyM1()
    }
    }

    Implicit Class In Scala

    In Scala we can declare a class with keyword implicit and can use implicitly to execute logic without actually calling it.

    See below example:

    We have created an implicit class IntWithTimes in object ImplicitExample and used the times() method of implicit in ImplicitExampleDemo.

    object ImplicitExample {
    implicit class IntWithTimes(x: Int) {
    def times[A](f: =&gt; A): Unit = {
    def loop(current: Int): Unit =
    if(current &gt; 0) {
    f
    loop(current - 1)
    }
    loop(x)
    }
    }
    }</code>
    
    import ImplicitExample._
    object ImplicitExampleDemo {
    def main(args: Array[String]): Unit = {
    4 times println("Hello")
    }
    }

    Output:

    Hello
    Hello
    Hello
    Hello

    References

    Next Article

    • Scala if else and loops













  • Leave a Reply

    Your email address will not be published. Required fields are marked *