Mohammed Hamdoon
Mohammed Hamdoon

Reputation: 75

List of objects of classes in Scala

I've created three classes A,B,C and in each class contains a list of elements , each class also contains a method that prints the elements , I've made a function outside the classes which has a pattern matching to choose which class to Print which takes a parameter of a list of the objects of the classes , my code is working well and can choose which class to print , but my question is what if the order of the objects of the classes in the list is not a,b,c but let's say c,a,b , how can someone then choose to print class A without knowing the order but just typing a ?

object printClass {
class A{
val a:List[Int] = List(1,2,3,4)
def printA(): Unit ={
  println("Class A")
  println(a)
}
}
class B{
val b:List[String] = List("Adam","Ali","Sara","Yara")
def printB(): Unit ={
  println("Class B")
  println(b)
}
}
class C{
val c:List[Char] = List('A','S','C','E')
def printC(): Unit ={
  println("Class C")
  println(c)
}
}
def prtClass(ch:Any): Unit ={
val a = new A()
val b = new B()
val c = new C()
ch match {
  case a: A => a.printA()
  case b: B => b.printB()
  case c: C => c.printC()
  case _ => print("Class not found")
}
}
def main(args: Array[String]): Unit = {
val a = new A()
val b = new B()
val c = new C()
val listOfObjects = List(a,b,c)
println("Choose the class to print (A,B,C) : ")
val choice:Int = scala.io.StdIn.readInt()
val ch = listOfObjects(choice)
prtClass(ch)
  }
}

Upvotes: 1

Views: 930

Answers (1)

Sandeep Kota
Sandeep Kota

Reputation: 76

TLDR; Use Map

Instead of using List to store a, b, c objects you could use Map. Keys as letters 'a' , 'b' , 'c' and values as objects a, b, c

val objects: Map[Char, Any] = Map('a' -> a, 'b' -> b, 'c' -> c)

And parse user input as Char

val choice = scala.io.StdIn.readChar()

Now now rest should fall in place. Objects will be fetched based on their association and same will be passed to prtClass function.

You could also define a parent class or trait to your A,B,C classes, so that Map value type can be confined to those types.

Upvotes: 1

Related Questions