What are Inner Classes in Scala?

An Inner Class refers to a class inside another class. This enables us to group classes that are only used in one place. By doing this, our code becomes encapsulated. This makes it easier to read, understand, and maintain.

Inner classes basically include a class inside an object or an object inside a class. The concept of inner classes in Scala varies from other languages. For example, in Java, the inner class is a member of the outer class, and the inner class in Scala is bound to the object of the outer class.

Syntax

class outerClass
{
     class innerClass
     {
        //Code
     }
}

Code

In the code below, Vehicle is an outer class and Car is an inner class.

Now, if we want to create an object of the inner class, Car, we need to create an object of the outer class, Vehicle.

First, we create the object of the outer class named obj. Next, obj is prefixed with the Car class. This creates the temp object of the Car class because the inner class is bound to the object of the outer class.

class Vehicle
{
class Car
{
var i : Int = 0;
def print()
{
for(i<-1 to 5)
{
println("This is My New Car : Honda");
}
}
}
}
object Main
{
def main(args: Array[String])
{
val obj = new Vehicle();
val temp = new obj.Car;
temp.print();
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved