Constructors

The concept and the usage of constructors in Scala are a little different than what they are in C# or Java. There are two types of constructors in Scala - primary and auxiliary constructors. The primary constructor is the class's body, and it's parameter list appears right after the class name.

For example, the following code segment describes the way to use the primary constructor in Scala:

class Animal (animalName:String, animalAge:Int) {  def getAnimalName () : String = {    animalName  }  def getAnimalAge () : Int = {    animalAge  }}

Now, to use the preceding constructor, this implementation is similar to the previous one, except there are no setters and getters. Instead, we can get the animal name and age, as here:

object RunAnimalExample ...

Get Scala and Spark for Big Data Analytics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.