Companion objects

When a singleton object is named the same as a class, it is called a companion object. A companion object must be defined inside the same source file as the class. Let's demonstrate this with the example here:

class Animal {
var animalName:String = "notset"
def setAnimalName(name: String) {
animalName = name
}
def getAnimalName: String = {
animalName
}
def isAnimalNameSet: Boolean = {
if (getAnimalName == "notset") false else true
}
}

The following is the way that you will call methods through the companion object (preferably with the same name - that is, Animal):

object Animal{
def main(args: Array[String]): Unit= {
val obj: Animal = new Animal
var flag:Boolean = false
obj.setAnimalName("dog")
flag = obj.isAnimalNameSet
println(flag) // prints true

obj.setAnimalName("notset")
flag = obj.isAnimalNameSet
println(flag) // prints false
}
}

A Java equivalent would be very similar, as follows:

public class Animal {
public String animalName = "null";
public void setAnimalName(String animalName) {
this.animalName = animalName;
}
public String getAnimalName() {
return animalName;
}
public boolean isAnimalNameSet() {
if (getAnimalName() == "notset") {
return false;
} else {
return true;
}
}

public static void main(String[] args) {
Animal obj = new Animal();
boolean flag = false;
obj.setAnimalName("dog");
flag = obj.isAnimalNameSet();
System.out.println(flag);

obj.setAnimalName("notset");
flag = obj.isAnimalNameSet();
System.out.println(flag);
}
}

Well done! So far, we have seen how to work with Scala objects and classes. However, working with the method for implementing and solving your data analytics problem is even more important. Thus, we will now see how to work with Scala methods in brief.

object RunAnimalExample {
val animalObj = new Animal
println(animalObj.getAnimalName) //prints the initial name
println(animalObj.getAnimalAge) //prints the initial age
// Now try setting the values of animal name and age as follows:
animalObj.setAnimalName("dog") //setting animal name
animalObj.setAnaimalAge(10) //seting animal age
println(animalObj.getAnimalName) //prints the new name of the animal
println(animalObj.getAnimalAge) //Prints the new age of the animal
}

The output is as follows:

notset 
-1
dog
10

Now, let's have a brief overview on the accessibility and the visibility of the Scala classes in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset