Scala – Nested Classes

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

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
scala> 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

scala> val fruit = a1.join(“Fruit”)

scala> val wolf = a1.join(“Wolf”)

scala> fruit.contacts += wolf

scala> val beer = b1.join(“Beer”)

scala> 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

scala> val wildanimal = new Animal

scala> val cat = petanimal.join(“Cat”)

scala> val dog = petanimal.join(“Dog”)

scala> cat.contacts += dog

scala> val lion = wildanimal.join(“Lion”)

scala> cat.contacts += lion

0
0

Quick Support

image image