Home > Software design >  I am implementing factory design pattern in Scala and got a compilation error when i tried to access
I am implementing factory design pattern in Scala and got a compilation error when i tried to access

Time:02-25

 abstract class Computers{
    def hdd:String
    def RAM:String
    def CPU:String
  } 
   class PC(storage:String,memory:String,Cores:String) extends Computers{
   def display:String="This is PC"
    var device="PC"
    def hdd={
      "Hard disk" " " storage 
    }
    def RAM={
     memory
    }
    def CPU={
     Cores
    }
  }
   class LAPTOP(storage:String,memory:String,Cores:String) extends Computers{
    def see:String={
      "Hi All"
    }
    var device="Laptop"
    def hdd={
     storage
    }
    def RAM={
     device  ":"  memory " RAM"
    }
    def CPU={
      Cores
    }
  }
  object Computers{    
    def apply(compType:String,storage:String,memory:String,Cores:String)={
      compType match{
        case "PC"=>new PC(storage:String,memory:String,Cores:String)
        case "LAPTOP"=>new LAPTOP(storage:String,memory:String,Cores:String)
      }
    }  
    def main(args:Array[String]){
      val c1=Computers("PC","1 TB","12 GB","5 GHz")
      val c2=Computers("LAPTOP","1 TB","12 GB","5 GHz")
      println(c1.display)
      println(c1.hdd)
      println(c2.RAM)

    }
    
  }

Hi All,i am new to scala and tried to implement factory design pattern. But when i tried to call child class method (display method of PC class)got below compilation error : 'Value display is not a member of Computers' Can some one help why i am getting the error

CodePudding user response:

You are getting this error because when you use the apply method of Computers you are getting an instance of type Computers which does not have the method display defined (as this is only defined on the subclass PC)

If you want access to this method you will need to have a PC and not a Computer type. You could achieve this in a few ways e.g.

  • Use the constructor of PC so that you have a type PC
  • Pattern match to make sure that a Computer is a PC
  • use .asInstanceOf[PC] so that you can call the method (not recommended as this can fail at runtime if whatever you are casting is not actually a PC
  • Related