Reader small image

You're reading from  Learning Scala Programming

Product typeBook
Published inJan 2018
Reading LevelBeginner
PublisherPackt
ISBN-139781788392822
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Vikash Sharma
Vikash Sharma
author image
Vikash Sharma

Vikash Sharma is a software developer and open source technology evangelist. He tries to keep things simple, which helps him write clean and manageable code. He has invested a large amount of time learning and implementing Scala code, and he has authored video courses for Scala. He works as a developer at SAP Labs.
Read more about Vikash Sharma

Right arrow

Chapter 6. Object-Oriented Scala Basics

"There is a central quality which is the root criterion of life and spirit of a man, a town, a building, or a wilderness. This quality is subjective and precise."

- The Timeless Way of Building

Scala is an obvious choice for many programmers because of the goodies it contains. It's a language that's functional as well as object-oriented, which means a lot to programmers. It gives us a way of building our applications in a modular and meaningful fashion. It's important to know that Scala's functional concepts are essential, powerful, and at the core of our programs. There is no doubt that algebraic data types have provided the essential abstractions and immutable data structures that have allowed the code to work in a concurrent environment. But real-world applications could need much more than that. Often, the amount of code we write makes it essential to have a way of managing it. That's where object-oriented abstractions come to the rescue. It's great...

Classes


To understand classes in Scala, let's make it clear that classes don't just do one thing for us. Classes work as a container for members in our programs, and as in any other object-oriented language, we can create instances of our class constructs and reuse them. By members we mean the variables and methods defined within. Why not take a look at a simple Scala class?

class Country(var name: String, var capital: String) 

Yes, the preceding code is a class that we defined named Country. It has two members named name and capital. Let's create a new country instance and print its values:

object CountryApp extends App { 
  val country = new Country("France", "Paris") 
  println(s"Country Name: ${country.name} and Capital: ${country.capital}") 
} 

On running the preceding code, we get the following result:

Country Name: France and Capital: Paris 

Now, believe me, it's going to be hard to resist Scala once I tell you that a class in Java with the same capabilities would need a few more lines...

Abstract classes


We can define abstract classes using the abstract keyword:

abstract class Person 
class Customer extends Person 
class Employee extends Person 

Here, what we wanted was two subclasses that can also be treated as instances of a superclass, in our case, Person. For now, we have not shown any behavior in our abstract class. But, there are times when we want to imply some behaviors in our abstract classes that subsequent subclasses can inherit and define for themselves:

abstract class Person(category: String) { 
  val idPrefix: String 
} 
 
class Customer extends Person("External") { 
  override val idPrefix: String = "CUST" 
} 
 
class Employee extends Person("Internal") { 
  override val idPrefix: String = "EMP" 
} 

Our intention to use abstract classes is clearer now. We may want a set of classes that inherit methods or values from a particular class. When we extend classes, we can use the override modifier in our definition. This kind of behavior is likely to present itself...

Objects as singletons


There are no static members or classes in Scala. Once you feel the need to create a static member, for example a static method or a class that is going to have only one instance, you should create an object. Yes, up until now, almost all the time we have been creating an object that extends the App trait so that we don't have to define the main method. This is the entry point to our application. So, it's also obvious that when we mention object, we don't mean an instance of any class; rather, an object in Scala has a different meaning.

An object, just like classes, is a container for functions and values. The reason why we may want to declare an object is so we can define utility methods for any particular type, or sometimes define JSON formatters and similar use cases. Let's take another look at how we can define an object:

object CountryUtil { 
   
} 

Looks like we just created an object. Nothing fancy, just an object keyword along with the name of the object. We know...

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 
} 
 
object CountryApp extends App { 
  val country = new Country("France", "Paris") 
  country.populationMap += ("2015" -> 64.39) += ("2016" -> 64.67) += ("2017" -> 64.93) 
 
  println(s"Country Name: ${country.name...

Case classes


What are case classes, why do we have them, and how do we use them? These are a few questions you may want an answer to. So, in simpler words, a case class can omit the amount of code we may have to write to achieve this:

class Country(val name: String, val capital: String) { 
 
  override def toString: String = s"Country($name,$capital)" 
 
  override def equals(obj: scala.Any): Boolean = ??? 
 
  override def hashCode(): Int = ??? 
 
} 

Instead of declaring Country as we do in the preceding code, we would prefer to do the following:

case class Country(name: String, capital: String) 

And our case class Country definition takes care of the rest. We have accessor methods for our name and capital members. We have our toString and equals methods defined by the Scala compiler, or let's say, auto-generated for us:

case class Country(name: String, capital: String) 
 
object CountryUtil extends App { 
  val country = Country("France", "Paris") 
  println(s"Our country is: $country") 
 ...

Summary


This chapter was interesting because we learned the details of Scala classes and object implementation. We started with what classes means in Scala, how we can declare them, and use them. Then we talked about objects as singleton instances in Scala. We then talked about interesting companion objects, which led us to case classes. We learned that case classes not only give us the conciseness we want but can also be very useful in scenarios where we may want to do pattern matching over instances. Finally, we discussed all the methods and goodies that case classes provide.

In the next chapter, we'll take our knowledge of object-oriented Scala to the next level and talk more about traits, inheritance, and a lot more.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning Scala Programming
Published in: Jan 2018Publisher: PacktISBN-13: 9781788392822
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Vikash Sharma

Vikash Sharma is a software developer and open source technology evangelist. He tries to keep things simple, which helps him write clean and manageable code. He has invested a large amount of time learning and implementing Scala code, and he has authored video courses for Scala. He works as a developer at SAP Labs.
Read more about Vikash Sharma