July 2017
Intermediate to advanced
796 pages
18h 55m
English
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 ...Read now
Unlock full access