1.

What Is The Use Of “object” Keyword In Scala? How To Create Singleton Objects In Scala?

Answer»

In Scala, object keyword is used the following purposes:

  • It is used to create singleton object in Scala.
  • object MySingletonObject
  • Here, MySingletonObject becomes singleton object automatically.

object keyword is used to DEFINE Scala Applications that is executable Scala programs.

object MyScalaExecutableProgram{
def main(args: Array[String]){
println("Hello World")
}
}

When we define main method in object as shown above (its same as main() method in Java), it becomes automatically as a executable Scala program.

It is used to define static MEMBERS LIKE static variables and static methods without using ‘static’ keyword.

object MyScalaStaticMembers{ 
VAL PI: Double = 3.1414 
def add(a: Int, b: Int) = a + b
}

By def PI VARIABLE and add methods will become as static members. That means we can call them without creating a separate object like MyScalaStaticMembers.add(10,20).

In Scala, object keyword is used the following purposes:

object keyword is used to define Scala Applications that is executable Scala programs.

object MyScalaExecutableProgram{
def main(args: Array[String]){
println("Hello World")
}
}

When we define main method in object as shown above (its same as main() method in Java), it becomes automatically as a executable Scala program.

It is used to define static members like static variables and static methods without using ‘static’ keyword.

object MyScalaStaticMembers{ 
val PI: Double = 3.1414 
def add(a: Int, b: Int) = a + b
}

By def PI variable and add methods will become as static members. That means we can call them without creating a separate object like MyScalaStaticMembers.add(10,20).



Discussion

No Comment Found