O'Reilly logo

Learning Scala Programming by Vikash Sharma

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Companion objects

Companion objects are not very different to what we have already seen when we discussed objects. One specific difference is that we name those the same as our class names. It means that instead of defining CountryUtil, we can give this object the same name as our Country class and call it our companion object:

class Country(val name: String, val capital: String){ var populationMap = scala.collection.mutable.Map[String, Double]() def getPopulation(year: String): Double = populationMap(year) //In Million override def toString: String = s"Country($name,$capital)" } object Country { /* * Function takes a sequence of population per million and returns average. * */ def populationAverage(pops: Seq[Double]) = pops.sum / pops.length ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required