Scala – Nested Classes

  • date 22nd April, 2021 |
  • by Prwatech |
  • 0 Comments

Scala - Nested Classes

 

In Scala, nesting can be done just about anything inside anything. functions can be define inside other functions, and classes inside other classes. Here are some simple examples.

use case 1:

scala> class eduprwa {
class Member(val name: String) {
val course = new ArrayBuffer[Member]
}
private val members = new ArrayBuffer[Member]

def join(name: String) = {
val m = new Member(name)
members += m

m
}
}
class eduprwa

scala> val BigData = new eduprwa
2scala> val DataScience = new eduprwa
scala> val Hadoop = new eduprwa

//In our eduprwa example, you can add a member within its own eduprwa, but not across networks.

use case 2:

scala> import scala.collection.mutable.ArrayBuffer

scala> class prwatech{

      class Member(val name: String){

      val contacts = new ArrayBuffer[Member]

      }

      private val members = new ArrayBuffer[Member]

      def join(name: String) = {

      val m = new Member(name)

      members +=m

      m

      }

      }

Scala>val a1 = new prwatech

scala> val b1 = new prwatech

2scala> val fruit = a1.join("Fruit")

scala> val wolf = a1.join("Wolf")

3scala> fruit.contacts += wolf

scala> val beer = b1.join("Beer")

4scala> a1.contacts += beer

use case 3:

scala> class Animal{

     class Member(val name: String){

     val contacts = new ArrayBuffer[Member]

     }

     private val members = new ArrayBuffer[Member]

     def join(name: String) = {

     val m = new Member(name)

     members +=m

     m

     }

     }

scala> val petanimal = new Animal

2scala> val wildanimal = new Animal

scala> val cat = petanimal.join("Cat")

3scala> val dog = petanimal.join("Dog")

scala> cat.contacts += dog

4scala> val lion = wildanimal.join("Lion")

scala> cat.contacts += lion

Quick Support

image image