In this shot, we will learn how to create various classes in Scala, an object-oriented language.
A class defines the structure of a program. It is basically the blueprint of your program, and it includes characteristics such as:
Note: In Scala, members are public by default. The keyword
privateneeds to be added before declaring a variable to limit its access within the class.
We can define multiple types of classes in Scala, such as:
Every class has one thing in common: the keyword class, which is used to define it.
In Scala, when we create a simple class, we define the class keyword followed by the name of the class. This structure is similar to how we create a class in C++ or Java.
Let’s look at the implementation of a simple class named Vehicle through the following example:
class Vehicle {var carName: String = "Wagon R"var companyName: String = "Suzuki"var carPlateNo: Int = 69def CarDetails() : Unit = {println("Name of the Car: " + carName);println("Name of Company: " + companyName);println("Car Number plate no: " + carPlateNo);}}object Main {def main(args: Array[String]) : Unit = {var obj = new Vehicle();obj.CarDetails();}}
The above code snippet implements a simple class, demonstrating how we can declare a function CarDetails and print the details of Vehicle that are stored in its variables.
Generic classes are classes that take a type – just like a parameter – inside the square brackets [].
This type of class is helpful for collection classes.
Generic classes in Scala have particular naming conventions when implementing a class.
[]) as a type parameterLet’s look at the implementation of generic classes through the following example:
object GenericClass {def main(args: Array[String]) : Unit = {abstract class Addition[A] {def addition(b: A, c: A): A}class intAddition extends Addition[Int] {def addition(b: Int, c: Int): Int = b + c}class doubleAddition extends Addition[Double] {def addition(b : Double, c : Double) : Double = b + c}val add1 = new intAddition().addition(69, 5)val add2 = new doubleAddition().addition(30.0, 8.0)println(add1)println(add2)}}
The above code snippet implements a generic class, demonstrating how we can use the same function (addition()) in multiple classes to add distinct data types and display their respective results.
Case classes in Scala are similar to regular classes, but they include a few new keywords.
Case classes are suitable for modeling
Note: All parameters listed in a case class are
publicand immutable by default. In a normal class, parameters are private by default.
The following is an example of adding two variables inside of a case class:
case class CaseClass (a:Int, b:Int)object MainObject {def main(args:Array[String]) : Unit = {var c = CaseClass(10,10)println("Sum of a & b = " + c.a + c.b)//println("b = " + c.b)}}
Free Resources